Run a function every x minutes: schedule or threading.Timer?

I need to program the execution of the give method every x minutes.

I found two ways to do this: the first uses the sched module, and the second uses Threading.Timer .

First method :

 import sched, time s = sched.scheduler(time.time, time.sleep) def do_something(sc): print "Doing stuff..." # do your stuff sc.enter(60, 1, do_something, (sc,)) s.enter(60, 1, do_something, (s,)) s.run() 

Second :

 import threading def do_something(sc): print "Doing stuff..." # do your stuff t = threading.Timer(0.5,do_something).start() do_something(sc) 

What is the difference and is one better than the other, which one?

+7
python timer python-multithreading
source share
1 answer

This is not safe in Python 2 - Python 3.2:

From the Python 2.7 sched :

In multi-threaded environments, the scheduler class has restrictions on thread safety, the inability to insert a new task before the one that is waiting in the running scheduler, and holding the main thread until the event queue is empty. Instead, the preferred approach is to use the threading.Timer class.

From the latest Python 3 sched

Changed in version 3.3: the scheduler class can be used safely in multi-threaded environments.

+9
source share

All Articles