I have a repeated python schedule task as following,which need to run getMyStock() every 3 minutes in startMonitor():
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( )
The questions are:
1.how could i cancel or stop the schedule when some user event comes?
2.Is there any other python module for better repeated scheduling?Just like java quartz?
Q1: scheduler.enter
returns the event object that is scheduled, so keep a handle on that and you can cancel
it:
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)
I've moved your code into a class to make referring to the event more convenient.
Q2 is outside of the scope of this site.
For cancelling a scheduled action
scheduler.cancel(event)
Removes the event from the queue. If event is not an event currently in the queue, this method will raise a ValueError Doc here
event
is a Return value of scheduler.enter
function which may be used for later cancellation of the event
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With