在日常工作中,我们常常需要执行周期性的任务,除了使用 linux 系统自带的 crond 结合命令行实现外,还可以直接使用 python 来完成这些任务。以下是常见的 python 定时任务实现方式的整理。
1、利用 while True: 和 sleep() 实现定时任务 time 模块中的 sleep(secs) 函数可以让当前线程暂停 secs 秒后继续执行。利用这种特性,我们可以通过 while 死循环结合 sleep() 来实现简单的定时任务。
代码示例:
import datetime import time <p>def time_printer(): now = datetime.datetime.now() ts = now.strftime('%Y-%m-%d %H:%M:%S') print('执行函数时间 :', ts)</p><p>def loop_monitor(): while True: time_printer() time.sleep(5) # 暂停 5 秒</p><p>if <strong>name</strong> == "<strong>main</strong>": loop_monitor()
主要缺点:
2、使用 Timeloop 库运行定时任务 Timeloop 是一个用于运行多周期任务的库,它通过 decorator 模式在线程中运行标记函数。
示例代码:
立即学习“Python免费学习笔记(深入)”;
import time from timeloop import Timeloop from datetime import timedelta</p><p>tl = Timeloop()</p><p>@tl.job(interval=timedelta(seconds=2)) def sample_job_every_2s(): print("2秒任务当前时间 : {}".format(time.ctime()))</p><p>@tl.job(interval=timedelta(seconds=5)) def sample_job_every_5s(): print("5秒任务当前时间 : {}".format(time.ctime()))</p><p>@tl.job(interval=timedelta(seconds=10)) def sample_job_every_10s(): print("10秒任务当前时间 : {}".format(time.ctime()))
3、利用 threading.Timer 实现定时任务 threading 模块中的 Timer 是一个非阻塞函数,比 sleep 稍好,可以启动多个异步执行的定时任务。
Timer(interval, function, args=[], kwargs={})
代码示例:
import datetime from threading import Timer</p><p>def time_printer(): now = datetime.datetime.now() ts = now.strftime('%Y-%m-%d %H:%M:%S') print('执行函数时间 :', ts) loop_monitor()</p><p>def loop_monitor(): t = Timer(5, time_printer) t.start()</p><p>if <strong>name</strong> == "<strong>main</strong>": loop_monitor()
备注:Timer 只能执行一次,需要循环调用才能实现定时任务。
4、利用内置模块 sched 实现定时任务 sched 模块提供了一个通用事件调度器,可以在指定时间执行任务,支持多线程。
class sched.scheduler(timefunc, delayfunc)
代码示例:
import datetime import time import sched</p><p>def time_printer(): now = datetime.datetime.now() ts = now.strftime('%Y-%m-%d %H:%M:%S') print('执行函数时间 :', ts) loop_monitor()</p><p>def loop_monitor(): s = sched.scheduler(time.time, time.sleep) # 生成调度器 s.enter(5, 1, time_printer, ()) s.run()</p><p>if <strong>name</strong> == "<strong>main</strong>": loop_monitor()
scheduler 对象的主要方法:
个人评价:比 threading.Timer 更优,不需要循环调用。
Python 作为一种多样化且发展良好的语言,肯定还有许多未提及的功能,如果大家有知道的,可以在评论区分享。
以上就是怎么把Python当偷懒神器用?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号