我想每2小时执行一次任务.Python有一个Timer in Threading模块,但是它能满足我的需求吗?我如何自己生成一个合适的计时器?
Nik*_*ohl 17
如果您希望每2小时运行一次代码,最简单的方法是使用cron或类似的调度程序,具体取决于您的操作系统
如果你希望你的程序每隔n秒调用一个函数(在你的情况下是7200)你可以使用一个线程和event.wait.以下示例启动每秒触发的计时器并将字符串输出到stdout
import threading
import time
class TimerClass(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.event = threading.Event()
def run(self):
while not self.event.is_set():
print "do something"
self.event.wait( 1 )
def stop(self):
self.event.set()
tmr = TimerClass()
tmr.start()
time.sleep( 10 )
tmr.stop()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9018 次 |
| 最近记录: |