本文统计并亲测了Python中常见的八种定时任务执行方法。
本人的校园网老是容易断开,一断开就需要重新去输入登录网址登录账户密码登录。一旦我离开学校就得经常找人操作我的主机电脑来登录。
找了找学校里好像有一个帮助你登录的脚本,这样就只需要定时启动一下就行,隔半小时启动一下,或者隔半小时PING一把,断了就启动登录脚本就行。
1、while True + time.sleep()
这可能是Python中比较常见且简单的方法了。
time 模块中的 sleep(secs) 函数,可以实现令当前执行的线程暂停 secs 秒后再继续执行。
所谓暂停,即令当前线程进入阻塞状态,当达到 sleep() 函数规定的时间后,再由阻塞状态转为就绪状态,等待 CPU 调度。
import datetime
import time
def time_printer():
now = datetime.datetime.now()
ts = now.strftime('%Y-%m-%d %H:%M:%S')
print('do func time :', ts)
def loop_monitor():
while True:
time_printer()
time.sleep(5) # 暂停5秒
if __name__ == "__main__":
loop_monitor()
这样只需要用 nohup 把Python程序挂起到后台即可。
主要缺点:
- 只能设定间隔,不能指定具体的时间,比如每天早上8:00
- sleep 是一个阻塞函数,也就是说 sleep 这一段时间,程序什么也不能操作。
2、使用Timeloop库运行定时任务
Timeloop是一个库,可用于运行多周期任务。这是一个简单的库,它使用decorator模式在线程中运行标记函数。
import time
from timeloop import Timeloop
from datetime import timedelta
tl = Timeloop()
@tl.job(interval=timedelta(seconds=2))
def sample_job_every_2s():
print "2s job current time : {}".format(time.ctime())
@tl.job(interval=timedelta(seconds=5))
def sample_job_every_5s():
print "5s job current time : {}".format(time.ctime())
@tl.job(interval=timedelta(seconds=10))
def sample_job_every_10s():
print "10s job current time : {}".format(time.ctime())
3、利用threading.Timer实现定时任务
threading 模块中的 Timer 是一个非阻塞函数,比 sleep 稍好一点,timer最基本理解就是定时器,我们可以启动多个定时任务,这些定时器任务是异步执行,所以不存在等待顺序执行问题。
Timer()
interval: 指定的时间
function: 要执行的方法
args/kwargs: 方法的参数
备注:Timer只能执行一次,这里需要循环调用,否则只能执行一次