是的,Python 有多个库可以用于定时执行任务。以下是几个常用的库:
1. time + sleep虽然简单,但可以通过 time.sleep() 实现基本的定时任务。
import time def task(): print("Task executed") while True: task() time.sleep(60) # 每60秒执行一次2. sched
sched 是 Python 标准库中的一个简单调度器。
import sched import time scheduler = sched.scheduler(time.time, time.sleep) def task(): print("Task executed") scheduler.enter(60, 1, task) # 每60秒执行一次 scheduler.enter(0, 1, task) scheduler.run()3. threading.Timer
threading.Timer 可以在单独的线程中定时执行任务。
import threading def task(): print("Task executed") threading.Timer(60.0, task).start() # 每60秒执行一次 task()4. schedule
schedule 是一个第三方库,提供了更友好的 API 来安排定时任务。
import schedule import time def task(): print("Task executed") schedule.every(1).minutes.do(task) # 每1分钟执行一次 while True: schedule.run_pending() time.sleep(1)5. APScheduler
APScheduler 是一个功能强大的第三方库,支持多种调度方式(如 cron 风格)。
from apscheduler.schedulers.blocking import BlockingScheduler def task(): print("Task executed") scheduler = BlockingScheduler() scheduler.add_job(task, 'interval', minutes=1) # 每1分钟执行一次 scheduler.start()6. celery
celery 是一个分布式任务队列,支持定时任务。
from celery import Celery from celery.schedules import crontab app = Celery('tasks', broker='pyamqp://guest@localhost//') @app.task def task(): print("Task executed") app.conf.beat_schedule = { 'add-every-minute': { 'task': 'tasks.task', 'schedule': crontab(minute='*/1'), # 每1分钟执行一次 }, }7. cron (Linux/Unix)
在 Linux/Unix 系统上,你可以使用 cron 来调度 Python 脚本。
# 编辑 crontab crontab -e # 添加以下行来每1分钟执行一次脚本 * * * * * /usr/bin/python3 /path/to/your_script.py总结如果你需要简单的定时任务,可以使用 time.sleep、sched 或 threading.Timer。如果你需要更复杂的调度,推荐使用 schedule 或 APScheduler。如果你需要分布式任务调度,可以考虑 celery。
根据你的需求选择合适的库。
网友回复
js如何流式输出ai的回答并折叠代码块,点击代码块右侧可预览代码?
ai大模型如何将文章转换成可视化一目了然的图片流程图图表?
大模型生成html版本的ui原型图和ppt演示文档的系统提示词怎么写?
rtsp视频直播流如何转换成websocket流在h5页面上观看?
为啥coze会开源工作流agent coze studio?
如何检测网页是通过收藏夹打开的?
python如何实现类似php的http动态脚本请求处理响应代码?
js如何实现类似php的http动态脚本请求处理响应代码?
trae与solo有啥区别不同?
vue如何让ai动态生成问卷调查多步骤表单式收集基础信息自动规划执行任务?