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

触发器类型

相关推荐
数据科学小丫39 分钟前
Python 数据存储操作_数据存储、补充知识点:Python 与 MySQL交互
数据库·python·mysql
Knight_AL42 分钟前
Nacos 启动问题 Failed to create database ’D:\nacos\nacos\data\derby-data’
开发语言·数据库·python
查古穆2 小时前
python进阶-Pydantic模型
开发语言·python
佳木逢钺2 小时前
PyQt界面美化系统高级工具库:打造现代化桌面应用的完整指南
python·pyqt
工頁光軍3 小时前
基于Python的Milvus完整使用案例
开发语言·python·milvus
Csvn3 小时前
特殊方法与运算符重载
python
xht08323 小时前
PHP vs Python:编程语言终极对决
开发语言·python·php
2401_879693873 小时前
使用Python控制Arduino或树莓派
jvm·数据库·python
查古穆4 小时前
python进阶-推导式
开发语言·python