python之定时任务schedule
1.安装
pip install schedule
2.基本操作
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import schedule import time def job(name): time.sleep(5) print("her name is : ", name) name = "longsongpong" # 秒 schedule.every(1).seconds.do(job, name) # 分 schedule.every(10).minutes.do(job, name) # 小时 schedule.every().hour.do(job, name) # 天 schedule.every().day.at("10:30").do(job, name) # 每5-10天就执行一次 schedule.every(5).to(10).days.do(job, name) # 每周一 schedule.every().monday.do(job, name) # 每周三13:15执行一次任务 schedule.every().wednesday.at("13:15").do(job, name) while True: schedule.run_pending() time.sleep(1)
3.原理
它是串行的,我们一般用多线程进行处理
4.直接用这种
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import datetime, time import schedule from threading import Thread key = "1" tm = datetime.datetime.now() def fun1(key): print(f"fun1:{tm}") def fun2(key): print(f"fun2:{tm}") #=================配置信息========================= # 现在这里写着吧,后面优化就放到配置文件里,函数放到公共的py文件里 # 配置多少秒跑一次 loop_second = 1 # 采用多线程来跑程序 def create_thread(fun): # 如果函数需要传参,则创建按一个字典对应的参数需要传什么 t = Thread(target=fun, args=key) t.start() # 配置一下所有要定时的函数 arr_fun = [fun1, fun2] if __name__ == '__main__': for fun in arr_fun: thread_fun = create_thread schedule.every(loop_second).seconds.do(thread_fun, fun) while True: schedule.run_pending()
-----------------------------------------------------------------------------------------------------------------------------------------