如何取消python时间表
问题内容:
我有一个重复的python计划任务,如下所示,它需要在startMonitor()中每3分钟运行一次getMyStock():
from stocktrace.util import settings
import time, os, sys, sched
schedule = sched.scheduler(time.time, time.sleep)
def periodic(scheduler, interval, action, actionargs=()):
scheduler.enter(interval, 1, periodic,
(scheduler, interval, action, actionargs))
action(*actionargs)
def startMonitor():
from stocktrace.parse.sinaparser import getMyStock
periodic(schedule, settings.POLLING_INTERVAL, getMyStock)
schedule.run( )
问题是:
1.当某些用户事件到来时,如何取消或停止计划?
2,还有其他python模块可以更好地重复调度吗?
问题答案:
问题1:scheduler.enter
返回已安排的事件对象,因此保留一个句柄就可以cancel
了:
from stocktrace.util import settings
from stocktrace.parse.sinaparser import getMyStock
import time, os, sys, sched
class Monitor(object):
def __init__(self):
self.schedule = sched.scheduler(time.time, time.sleep)
self.interval = settings.POLLING_INTERVAL
self._running = False
def periodic(self, action, actionargs=()):
if self._running:
self.event = self.scheduler.enter(self.interval, 1, self.periodic, (action, actionargs))
action(*actionargs)
def start(self):
self._running = True
self.periodic(getMyStock)
self.schedule.run( )
def stop(self):
self._running = False
if self.schedule and self.event:
self.schedule.cancel(self.event)
我已将您的代码移到一个类中,以使引用事件更加方便。
Q2不在此站点范围内。