简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM