调度器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()

触发器类型

相关推荐
2601_962300811 小时前
机器学习贴士:使用Python编写MapReduce
hadoop·python·机器学习·mapreduce·数据处理
xyz_CDragon2 小时前
GitHub上4个爆款AI开源Skill:拍照后不用P图,用Codex一键生成高级海报(附效果图+使用教程)
人工智能·python·github·codex·skill
weixin199701080162 小时前
[特殊字符]《跨境二手ERP对接Back Market:标准化API + 7~10工作日技术合规审核实录》(附Python源码)
开发语言·python·pandas
持敬chijing3 小时前
Python-数据类型-列表
开发语言·python·青少年编程
2601_962301013 小时前
Python环境搭建及PyCharm破解使用技巧
python·pycharm·环境搭建·避坑技巧·破解使用
2601_962099465 小时前
Python中的find()函数:用法和示例
python·字符串·索引·子字符串·find函数
大圣编蚕5 小时前
Java StringWriter 详解:从入门到实战
java·开发语言·python
for_ever_love__6 小时前
python基础语法学习: requirements.txt
开发语言·python·学习
程序员清风6 小时前
FastAPI 入门:用 Python 快速开发现代后端服务
python·oracle·fastapi
SunnyDays10116 小时前
使用 Python 提取 Word 文档中的表格数据
python·word