Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Schedule a repeating event in Python 3

I'm trying to schedule a repeating event to run every minute in Python 3.

I've seen class sched.scheduler but I'm wondering if there's another way to do it. I've heard mentions I could use multiple threads for this, which I wouldn't mind doing.

I'm basically requesting some JSON and then parsing it; its value changes over time.

To use sched.scheduler I have to create a loop to request it to schedule the even to run for one hour:

scheduler = sched.scheduler(time.time, time.sleep)  # Schedule the event. THIS IS UGLY! for i in range(60):     scheduler.enter(3600 * i, 1, query_rate_limit, ())  scheduler.run() 

What other ways to do this are there?

like image 452
Humphrey Bogart Avatar asked Mar 08 '10 00:03

Humphrey Bogart


People also ask

What is sched module in Python?

Sched module is the standard library, can be used in the creation of bots and other monitoring and automation applications. The sched module implements a generic event scheduler for running tasks at specific times.


2 Answers

You could use threading.Timer, but that also schedules a one-off event, similarly to the .enter method of scheduler objects.

The normal pattern (in any language) to transform a one-off scheduler into a periodic scheduler is to have each event re-schedule itself at the specified interval. For example, with sched, I would not use a loop like you're doing, but rather something like:

def periodic(scheduler, interval, action, actionargs=()):     scheduler.enter(interval, 1, periodic,                     (scheduler, interval, action, actionargs))     action(*actionargs) 

and initiate the whole "forever periodic schedule" with a call

periodic(scheduler, 3600, query_rate_limit) 

Or, I could use threading.Timer instead of scheduler.enter, but the pattern's quite similar.

If you need a more refined variation (e.g., stop the periodic rescheduling at a given time or upon certain conditions), that's not too hard to accomodate with a few extra parameters.

like image 180
Alex Martelli Avatar answered Sep 16 '22 17:09

Alex Martelli


You could use schedule. It works on Python 2.7 and 3.3 and is rather lightweight:

import schedule import time  def job():    print("I'm working...")  schedule.every(10).minutes.do(job) schedule.every().hour.do(job) schedule.every().day.at("10:30").do(job)  while 1:    schedule.run_pending()    time.sleep(1) 
like image 20
dbader Avatar answered Sep 17 '22 17:09

dbader