Python schedule 库是一个轻量级的任务调度工具,允许你以简单直观的方式安排代码在特定时间或周期性地自动执行。
1、schedule常规使用方法
# -*- coding:utf-8 -*-
import schedule
# 每秒钟运行一次
schedule.every(1).seconds.do(job)
# 每分钟运行一次
schedule.every(1).minutes.do(job)
# 每小时运行一次
schedule.every(1).hours.do(job)
# 每天的3点运行一次(24小时计时法)
schedule.every().day.at("03:00").do(job)
# 每周一的早上3点运行一次
schedule.every().monday.at("03:00").do(job)
2、schedule实例,每3秒运行一次任务
# -*- coding:utf-8 -*-
import schedule,time
def job():
now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print(f'当前时间:{now}')
# 每3秒运行一次
schedule.every(3).seconds.do(job)
while True:
schedule.run_pending()
time.sleep(0.1)
> 运行结果:
当前时间:2021-05-31 10:47:42
当前时间:2021-05-31 10:47:45
当前时间:2021-05-31 10:47:48
当前时间:2021-05-31 10:47:51
当前时间:2021-05-31 10:47:54
当前时间:2021-05-31 10:47:57
当前时间:2021-05-31 10:48:00