To execute a function every x minutes: sched or threading.Timer?

farhawa picture farhawa · Jan 27, 2016 · Viewed 8.9k times · Source

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

I found two ways to do it: the first is using the sched module, and the second is using 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()

The 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's the difference and if there is one better than the other, which one?

Answer

Peter Wood picture Peter Wood · Jan 27, 2016

It's not safe in Python 2 - Python 3.2:

From the Python 2.7 sched documentation:

In multi-threaded environments, the scheduler class has limitations with respect to thread-safety, inability to insert a new task before the one currently pending in a running scheduler, and holding up the main thread until the event queue is empty. Instead, the preferred approach is to use the threading.Timer class instead.

From the latest Python 3 sched documentation

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