还在用 time.sleep() 写定时任务?
你的代码正在被同事偷偷嘲笑。
别慌,今天带你解锁 Python 定时任务的 5 种高级姿势——
尤其第 4 种,我第一次用完直接拍大腿:这也太狠了吧!
🕒 为什么 time.sleep() 是个“伪定时”?
time.sleep() 会阻塞主线程,程序卡死不说,还不能精准控制时间。
比如你想每 5 秒执行一次任务:
import time
whileTrue:
print("干活了!")
time.sleep(5)
一旦任务本身耗时 3 秒,实际间隔就变成 8 秒。
更别说异常中断、无法并行、调试困难……
它根本不是为生产环境设计的。
⏱️ 解法一:threading.Timer —— 轻量但脆弱
Python 自带的 Timer 可以延迟执行函数:
import threading
deftask():
print("定时任务跑啦!")
# 递归调用实现循环
threading.Timer(5, task).start()
task()
优点:简单、不阻塞主线程。
缺点:异常处理麻烦,长期运行容易内存泄漏。
适合:一次性或短周期脚本,别上生产!
🔁 解法二:schedule 库 —— 人类友好的 DSL
装个第三方库,写定时像写自然语言:
pip install schedule
import schedule
import time
defjob():
print("老板,我又干完活了!")
schedule.every(10).seconds.do(job)
whileTrue:
schedule.run_pending()
time.sleep(1) # 这里的 sleep 影响极小
支持:秒/分/小时/周/特定时间(比如每天 9:30)。
真实案例:我们团队用它跑日报脚本,稳如老狗。
注意:仍需一个 while 循环,但逻辑清晰多了。
🧵 解法三:APScheduler —— 企业级定时神器
全称 Advanced Python Scheduler,支持多线程、进程、持久化。
from apscheduler.schedulers.blocking import BlockingScheduler
defmy_job():
print("高并发定时任务启动!")
sched = BlockingScheduler()
sched.add_job(my_job, 'interval', seconds=5)
sched.start()
牛在哪?
- 支持 Cron 表达式(
'0 9 * * *' 每天 9 点)
某电商公司用它调度百万级订单对账,零故障运行两年+。
如果你在写后端服务,闭眼选它。
💥 解法四:asyncio + aiojobs —— 异步定时,性能炸裂!
这才是真正的狠活🔥。
用异步非阻塞方式跑定时任务,资源占用极低:
import asyncio
import aiojobs
asyncdeftick():
print("异步心跳:滴答!")
asyncdefscheduler():
scheduler = await aiojobs.create_scheduler()
whileTrue:
await scheduler.spawn(tick())
await asyncio.sleep(2)
asyncio.run(scheduler())
优势:
- 不阻塞 I/O,适合 Web 后台、爬虫、实时系统
实测数据:同样 1000 个 1 秒任务,
time.sleep 耗时 >16 分钟,
而 aiojobs不到 2 秒!🤯
🤖 解法五:交给操作系统 —— cron 或 Celery Beat
终极方案:别自己搞定时!
把任务交给更专业的调度器:
Linux 用 cron:
# 每分钟跑一次
* * * * * /usr/bin/python3 /path/to/script.py
分布式系统用 Celery + Redis/RabbitMQ:
# celeryconfig.py
from celery.schedules import crontab
beat_schedule = {
'my-task': {
'task': 'tasks.my_periodic_task',
'schedule': crontab(minute='*/5'),
}
}
为什么靠谱?
大厂标配,小团队也能用。
🎯 总结:别再“睡”着写代码了!
time.sleep() 就像用胶带修水管——能用,但迟早漏。
根据场景选工具: