打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
python中的定时任务

使用threading模块中的Timer函数

from threading import Timerimport timedef execute_func(name, age, gender, hobby):    print(f"name is {name}, age is {age}, gender is {gender}, hobby is {hobby}")def start_func():    # Timer接收的参数是:interval, function, args=None, kwargs=None    # interval:时间间隔,一个数字,表示多少秒后执行    # function:函数,要执行的函数    # args:位置参数    # kwargs:关键字参数    t = Timer(3, execute_func, args=("satori", 10), kwargs={"gender": "f", "hobby": "animal"})    # 调用start之后启动,并且不会阻塞,因为单独开启了一个线程    t.start()    time.sleep(5)    print("在我打印之前,execute_func函数就已经被执行完毕了")start_func()

运行结果

name is satori, age is 10, gender is f, hobby is animal在我打印之前,execute_func函数就已经被执行完毕了

使用schedule模块

import scheduledef foo():    print(123)# 每隔3秒钟运行foo,如果有参数,直接通过args= 或者kwargs=进行传参即可schedule.every(3).seconds.do(foo)# 每隔1秒钟运行fooschedule.every().seconds.do(foo)# 每隔1分钟运行fooschedule.every().minutes.do(foo)# 每隔一小时运行fooschedule.every().hours.do(foo)# 每隔一天运行fooschedule.every().days.do(foo)# 每隔一星期运行fooschedule.every().weeks.do(foo)# 每隔3到5秒钟运行fooschedule.every(3).to(5).seconds.do(foo)# 每隔3到5天运行fooschedule.every(3).to(5).days.do(foo)# 每天在10:30的时候运行fooschedule.every().days.at("10:30").do(foo)# 每周一的时候运行fooschedule.every().monday.do(foo)# 每周日晚上11点的时候运行fooschedule.every().sunday.at("23:00").do(foo)while True:    # 保持schedule一直运行,然后去查询上面的任务    schedule.run_pending()
import scheduleimport timedef foo1():    time.sleep(2)    print(time.perf_counter() - start_time)def foo2():    time.sleep(2)    print(time.perf_counter() - start_time)schedule.every(5).seconds.do(foo1)schedule.every(5).seconds.do(foo2)start_time = time.perf_counter()while 1:    schedule.run_pending()

运行结果

7.0001335409999999.00049648514.00149056299999916.00247799121.00255695323.00314625128.00330860630.003953593

注意到:运行时间是每隔七秒后,由于任务本身也占用了时间。可以考虑使用多线程

import scheduleimport timeimport threadingdef foo1():    time.sleep(2)    print(time.perf_counter() - start_time)def foo2():    time.sleep(2)    print(time.perf_counter() - start_time)def t1():    t = threading.Thread(target=foo1)    t.start()    def t2():    t = threading.Thread(target=foo2)    t.start()schedule.every(5).seconds.do(t1)schedule.every(5).seconds.do(t2)start_time = time.perf_counter()while 1:    schedule.run_pending()

运行结果

7.0063930737.00645153200000112.00721703899999912.01226084799999917.0066992217.01270746322.00817149800000322.008225246000002

可以看到这次变成每隔5秒执行了,而且两个任务之间也没有2s的间隔了

来源:http://www.icode9.com/content-1-231251.html
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
十步,教你把Python运行速度提升 30%
Python之闭包与延时绑定问题
Python装饰器
Python基础知识之难点备忘
Python学习笔记《Python核心编程》第11章 函数和函数式编程
python中的可变队相遇不可变对象
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服