最常用的是以下的方法。不过缺点是sleep函数堵塞了主线程,会造成无妨同时运行其他的程序。
#!/usr/bin/env python
#-- encoding:utf-8 --
import time
def task():
print "task ..."
def timer(n):
while True:
print time.strftime('%Y-%m-%d %X',time.localtime())
task()
time.sleep(n)
if __name__ == '__main__':
timer(5)
下面使用threading来执行,并且延时执行,不会对主线程堵塞。
import threading
def sayHello():
print "Hello"
t=threading.Timer(20,sayHello)
t.start()
def other_func():
print "Other"
if __name__=="__main__":
sayHello()
other_func()
原文地址:Python定时任务
1259

被折叠的 条评论
为什么被折叠?



