Skip to content Skip to sidebar Skip to footer

How To Cancel Python Schedule

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, sch

Solution 1:

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

classMonitor(object):
    def__init__(self):
        self.schedule = sched.scheduler(time.time, time.sleep)
        self.interval = settings.POLLING_INTERVAL
        self._running = Falsedefperiodic(self, action, actionargs=()):
        if self._running:
            self.event = self.scheduler.enter(self.interval, 1, self.periodic, (action, actionargs))
            action(*actionargs)

    defstart(self):
        self._running = True
        self.periodic(getMyStock)
        self.schedule.run( )

    defstop(self):
        self._running = Falseif 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.

Solution 2:

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

Post a Comment for "How To Cancel Python Schedule"