How to cancel python schedule

I have a python schedule re-task, as shown below, which should getMyStock () run 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( ) 

Questions:

1. How can I cancel or stop the schedule when some user event arrives?

2. Is there any other python module for better re-planning? Also like java quartz?

+6
source share
2 answers

Q1: scheduler.enter returns the event object that is scheduled, so hold the handle 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 moved your code to a class to make the event call more convenient.

Q2 is outside the scope of this site.

+6
source

Cancel a scheduled action

scheduler.cancel(event)

Removes an event from the queue. If the event is not an event in the queue in the queue, this method will raise the Doc value here

event is the return value of the scheduler.enter function, which can be used to subsequently cancel the event

+1
source

Source: https://habr.com/ru/post/927806/


All Articles