far*_*awa 8 python timer python-multithreading
我需要每隔x分钟编写一次给定方法的执行.
我找到了两种方法:第一种是使用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()
Run Code Online (Sandbox Code Playgroud)
第二个:
import threading
def do_something(sc):
print "Doing stuff..."
# do your stuff
t = threading.Timer(0.5,do_something).start()
do_something(sc)
Run Code Online (Sandbox Code Playgroud)
有什么区别,如果有一个比另一个好,哪一个?
Pet*_*ood 11
它在Python 2中不安全 - Python 3.2:
在多线程环境中,
scheduler该类在线程安全性方面存在限制,无法在正在运行的调度程序中当前挂起的任务之前插入新任务,并且在事件队列为空之前保持主线程.相反,首选方法是使用threading.Timer该类.
版本3.3中更改:
scheduler类可以安全地用于多线程环境.
| 归档时间: |
|
| 查看次数: |
5640 次 |
| 最近记录: |