admin管理员组文章数量:1574568
python中有一个轻量级的定时任务调度的库:schedule。他可以完成每分钟,每小时,每天,周几,特定日期的定时任务。因此十分方便我们执行一些轻量级的定时任务.
代码如下:
import schedule
import time
def job(name):
print("her name is : ", name)
name = "longsongpong"
schedule.every(10).minutes.do(job, name)
schedule.every().hour.do(job, name)
schedule.every().day.at("10:30").do(job, name)
schedule.every(5).to(10).days.do(job, name)
schedule.every().monday.do(job, name)
schedule.every().wednesday.at("13:15").do(job, name)
while True:
schedule.run_pending()
time.sleep(1)
每隔十分钟执行一次任务
每隔一小时执行一次任务
每天的10:30执行一次任务
每隔5到10天执行一次任务
每周一的这个时候执行一次任务
每周三13:15执行一次任务
run_pending:运行所有可以运行的任务
schedule方法是串行的,也就是说,如果各个任务之间时间不冲突,那是没问题的;如果时间有冲突的话,会串行的执行命令
代码如下:
import schedule
import time
import threading
def job():
print("I'm working... in job1 start")
time.sleep(15)
print("I'm working... in job1 end")
def job2():
print("I'm working... in job2")
schedule.every(10).seconds.do(job)
schedule.every(10).seconds.do(job2)
while True:
schedule.run_pending()
time.sleep(1)
结果如下:
I’m working… in job1 start
I’m working… in job1 end
I’m working… in job2
如果要多线程并发运行
代码如下:
import schedule
import time
import threading
def job():
print("I'm working... in job1 start")
time.sleep(15)
print("I'm working... in job1 end")
def job2():
print("I'm working... in job2")
def run_threaded(job_func):
job_thread = threading.Thread(target=job_func)
job_thread.start()
schedule.every(10).seconds.do(run_threaded,job)
schedule.every(10).seconds.do(run_threaded,job2)
while True:
schedule.run_pending()
time.sleep(1)
结果如下:
I’m working… in job1 start
I’m working… in job2
I’m working… in job1 start
I’m working… in job2
I’m working… in job1 end
I’m working… in job1 start
I’m working… in job2
版权声明:本文标题:python中使用schedule模块定时执行任务 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/dianzi/1725781719a1042265.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论