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

限于喜欢 提交于 2019-12-21 10:16:00

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/35036348/to-execute-a-function-every-x-minutes-sched-or-threading-timer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!