每 x 分钟执行一次函数:sched 还是 threading.Timer? [英] To execute a function every x minutes: sched or threading.Timer?
问题描述
我需要每 x 分钟编写一次给定方法的执行.
I need to program the execution of a give method every x minutes.
我找到了两种方法:第一种是使用 sched
模块,第二种是使用 Threading.Timer
.
I found two ways to do it: the first is using the sched
module, and the second is using Threading.Timer
.
第一种方法:
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()
第二个:
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?
推荐答案
Python 2 - Python 3.2 不安全:
It's not safe in Python 2 - Python 3.2:
在多线程环境中,scheduler
类在线程安全方面存在局限性,无法在正在运行的调度程序中当前挂起的任务之前插入新任务,并且会阻塞主线程直到事件队列为空.相反,首选方法是使用 threading.Timer
类.
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 thethreading.Timer
class instead.
在 3.3 版中更改: scheduler
类可以在多线程环境中安全使用.
Changed in version 3.3:
scheduler
class can be safely used in multi-threaded environments.
这篇关于每 x 分钟执行一次函数:sched 还是 threading.Timer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!