每 x 分钟执行一次函数:sched 或 threading.Timer?
To execute a function every x minutes: sched or threading.Timer?
我需要编写每 x 分钟执行一次 give 方法的程序。
我找到了两种方法:第一种是使用 sched
模块,第二种是使用 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)
有什么区别,如果有一个比另一个更好,那是哪个?
在 Python 2 - Python 3.2:
中不安全
来自 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.
来自the latest Python 3 sched
documentation
Changed in version 3.3: scheduler
class can be safely used in multi-threaded environments.
我需要编写每 x 分钟执行一次 give 方法的程序。
我找到了两种方法:第一种是使用 sched
模块,第二种是使用 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)
有什么区别,如果有一个比另一个更好,那是哪个?
在 Python 2 - Python 3.2:
中不安全来自 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 thethreading.Timer
class instead.
来自the latest Python 3 sched
documentation
Changed in version 3.3:
scheduler
class can be safely used in multi-threaded environments.