文章背景: 在日常工作中,有时我们需要定时运行
某个程序。比如某个表格每天会随时更新,我们需要定时查看,从而获得最新的数据。下面介绍两个方法实现定时运行程序。
1 while True: + sleep()实现定时任务
2 threading模块中的Timer
位于 time 模块中的 sleep(secs) 函数,可以实现令当前执行的线程暂停 secs 秒后再继续执行。所谓暂停,即令当前线程进入阻塞状态,当达到 sleep() 函数规定的时间后,再由阻塞状态转为就绪状态,等待 CPU 调度。
基于这样的特性我们可以通过while死循环+sleep()的方式实现简单的定时任务。
下面的代码块实现的功能是:每5秒打印一次时间。
from datetime import datetime
import time
# 每n秒执行一次
def timer(n):
while True:
print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
time.sleep(n)
# 主程序
timer(5)
注:The strftime()
method returns a string representing date and time using date, time or datetime object.
上述代码块的运行效果:
这个方法的缺点是,只能执行固定间隔时间
的任务,并且 sleep 是一个阻塞函数,也就是说在 sleep 这一段时间,当前程序无法执行其他任务。
threading 模块中的 Timer 是一个非阻塞函数,这一点比 sleep 稍好一些。缺点也是只能执行固定间隔时间
的任务。
Timer 函数第一个参数是时间间隔(单位是秒),第二个参数是要调用的函数名,第三个参数是调用函数的位置参数(可以使用元组或列表)。
threading.Timer
(interval, function, args=None, kwargs=None)
Create a timer that will run function with arguments args and keyword arguments kwargs, after interval seconds have passed. If args is None
(the default) then an empty list will be used. If kwargs is None
(the default) then an empty dict will be used.
下面的代码块实现的功能是:每5秒打印一次当前时间。
from datetime import datetime
from threading import Timer
# 打印时间函数
def print_time(inc):
print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
t = Timer(inc, print_time, (inc,))
t.start()
# 5s
print_time(5)
运行效果:
上述代码块中运用了递归
的思想。在print_time
函数中,当打印出当前时间后,又设置了定时器线程Timer,这就完成了一个递归的操作,间隔5秒重复执行定时任务。
下面的代码块实现类似的功能:每5秒打印一次当前时间。
import time
import threading
def create_timer(inc):
t = threading.Timer(inc, repeat, [inc])
t.start()
def repeat(inc):
print('Now:', time.strftime('%H:%M:%S', time.localtime()))
create_timer(inc)
create_timer(5)
运行效果:
参考资料:
[1] Python 实现定时任务的八种方案(https://cloud.tencent.com/developer/article/1887717)
[2] Python: 定时任务的实现方式(https://justcode.ikeepstudying.com/2019/10/python-%E5%AE%9A%E6%97%B6%E4%BB%BB%E5%8A%A1%E7%9A%84%E5%AE%9E%E7%8E%B0%E6%96%B9%E5%BC%8F-crontab-%E4%BB%BB%E5%8A%A1-%E5%AE%9A%E6%97%B6%E8%BF%90%E8%A1%8C/)
[3] Python strftime() (https://www.programiz.com/python-programming/datetime/strftime)
[4] threading (https://docs.python.org/3/library/threading.html#timer-objects)
[5] python 线程定时器Timer (https://zhuanlan.zhihu.com/p/91412537)
[6] time (https://docs.python.org/3/library/time.html#module-time)