在进程中定期执行任务
我想每两小时执行一次任务。Python里面有一个叫做Timer的东西,在Threading模块里,但这个能满足我的需求吗?我该怎么自己创建一个合适的Timer呢?
2 个回答
0
这可能是一个解决方案……
import time
def fun1():
print "Hi "
while 1:
fun1()
time.sleep(5)
这个fun1函数会每隔5秒执行一次。不过我不太确定这样在特定时间后调用一个函数是否是个好方法。这个方案有什么缺点吗?
18
如果你想让你的代码每两小时运行一次,最简单的方法就是使用cron或者根据你的操作系统选择类似的调度工具。
如果你想让你的程序每n秒(在你的例子中是7200秒)调用一次某个函数,你可以使用线程和event.wait。下面的例子启动了一个定时器,每秒触发一次,并将一个字符串打印到标准输出。
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()