Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 429
farhawa Avatar asked Jan 27 '16 11:01

farhawa


1 Answers

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.

like image 150
Peter Wood Avatar answered Oct 03 '22 00:10

Peter Wood