python开发中用到,定时操作。例如每隔1s执行一次,发现 threading.Timer,这个东西,可以直接用。
threading.Timer 实现:
其原理为执行函数中置定时函数Timer(),递归调用自己,看来实现方法比较奇怪。
from datetime import datetime
from threading import Timer
# 打印时间函数
# OK
def printTime(inc):
print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
global indexValue
print("第", indexValue, "次运行")
indexValue=indexValue+1
t = Timer(inc, printTime, (inc,))
t.start()
indexValue=1
printTime(1)
sched实现;
使用死循环
from datetime import datetime
import sched
import time
'''
每个 10 秒打印当前时间。 OK
'''
def timedTask():
# 初始化 sched 模块的 scheduler 类
while True:
scheduler = sched.scheduler(time.time, time.sleep)
# 增加调度任务
scheduler.enter(10, 1, task)
# 运行任务
scheduler.run()
# 定时任务
def task():
print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
if __name__ == '__main__':
timedTask()
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/101640.html