调度器APScheduler定时执行任务

APScheduler(Advanced Python Scheduler)是一个Python库,用于调度任务,使其在预定的时间间隔或特定时间点执行。它支持多种调度方式,包括定时(interval)、日期(date)和Cron风格的调度(cron)。

APScheduler的主要组件

Schedulers(调度器):

BlockingScheduler:最简单的调度器,会阻塞当前线程,适用于单独的调度任务。

BackgroundScheduler:在后台运行,不阻塞当前线程,适用于需要在其他程序中运行的调度任务。

AsyncIOScheduler、GeventScheduler、TwistedScheduler:用于与特定的异步框架集成。

Jobs(任务):

表示要在某个时间执行的任务,可以是函数或方法。

Triggers(触发器):

决定任务何时执行。有三种主要触发器类型:

date:在特定时间执行一次。

interval:以固定的时间间隔重复执行。

cron:基于Cron表达式,在特定的时间点执行。

实践

python 复制代码
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.interval import IntervalTrigger

scheduler = BackgroundScheduler(timezone=pytz.timezone("Asia/Shanghai"))
# 解决错误: raise TypeError('Only timezones from the pytz library are supported' )ypeError: Only timezones from the pytz library are supported
# 运行任务
scheduler.add_job(task1, 'cron', hour='8' , minute='30') # 每天发送一次
scheduler.add_job(task2, 'cron', hour='8', minute='30') # 每天发送一次

try:
    scheduler.start()
    normal_log.logger.info('调度器已启动...')

    # 使脚本持续运行
    while True:
        time.sleep(2)
except (KeyboardInterrupt, SystemExit):
    scheduler.shutdown()

触发器类型

相关推荐
金銀銅鐵1 天前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup111 天前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi001 天前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵1 天前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf1 天前
Agent 流程编排
后端·python·agent
copyer_xyf1 天前
Agent RAG
后端·python·agent
copyer_xyf1 天前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf1 天前
Agent 记忆管理
后端·python·agent
星云穿梭2 天前
用Python写一个带图形界面的学生管理系统——完整教程
python