Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.8k views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...