打开APP
userphoto
未登录

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

开通VIP
记录下python3中使用定时器的几种方法

方式一、直接使用while循环的方式

from datetime import datetimeimport time# 每n秒执行一次def timer(n):    while True:        print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))        time.sleep(n)timer(5)

方式二、使用threading模块中的Timer

from datetime import datetimefrom threading import Timer# 打印时间函数def print_time(inc):    print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))    """    Timer的参数说明    inc:表示时间间隔    print_time:执行的函数    (inc,):传递给执行函数的参数    """    t = Timer(inc, print_time, (inc,))    t.start()print_time(2)

方式三、使用sched模块

import timeimport schedfrom datetime import datetime# 初始化 sched 模块的 scheduler 类# 第一个参数是一个可以返回时间戳的函数,第二个参数可以在定时未到达之前阻塞。schedule = sched.scheduler(time.time, time.sleep)# 被周期性调度触发的函数def print_time(inc):    print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))    schedule.enter(inc, 0, print_time, (inc,))# 默认参数 60 sdef start(inc=60):    # enter四个参数分别为:间隔事件、优先级(用于同时间到达的两个事件同时执行时定序)、被调用触发的函数、给触发函数的参数(tuple形式)    schedule.enter(0, 0, print_time, (inc,))    schedule.run()if __name__ == "__main__":    start(10)

方式四、使用apscheduler

from apscheduler.schedulers.blocking import BlockingSchedulerfrom datetime import datetimedef job():    print(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))if __name__ == "__main__":    scheduler = BlockingScheduler()    scheduler.add_job(job, 'interval', seconds=5)    scheduler.start()
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
python模块---datetime
第49天:Python 多线程之 threading 模块
time date datetme timestamp 傻傻分不清楚
Python中strftime() 函数的21个参数详细讲解
测量Python代码运行的时间
C站最全Python库总结丨标准库+高级库
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服