Python定时任务调度:apscheduler常见的使用示例

一、介绍

APScheduler用起来十分方便,提供了基于日期,时间间隔及crontab类型的任务。为我们提供了构建专用调度器或者调度服务的基础模块。

APScheduler不是一个守护进程或服务,它自身不带有任何命令行工具。它主要在现有的程序中运行,

安装:pip3 install apscheduler

官网文档:apscheduler.triggers.cron — APScheduler 3.9.0.post1.post1 documentation

二、基本示例

下面给出了常见的几种定时任务控制的示例:

# -*- coding: UTF-8 -*-
"""
@Time : 2022/9/21 15:54
@Auth : rs
"""
from logzero import logger
from apscheduler.schedulers.blocking import BlockingScheduler

sched = BlockingScheduler()


def hello_1():
    logger.info("hello_1...")


def hello_2():
    logger.info("hello_2...")


def hello_3():
    logger.info("hello_3...")


def hello_4():
    logger.info("hello_4...")


# 每天上午9:00-21:00,每隔3min运行一次
sched.add_job(hello_1, 'cron', day_of_week='*', hour='9-21', minute='*/3')

# 周一到周五,上午9:00-21:00,每隔10秒运行一次
sched.add_job(hello_2, 'cron', day_of_week='mon-fri', hour='9-21', minute='*', second='*/10')

# 周一到周五, 每天上午9:00和晚上21:00各运行一次
sched.add_job(hello_3, 'cron', day_of_week='mon-fri', hour='8,20')

# 每隔5min运行一次
sched.add_job(hello_4, 'interval', minutes=5)

# 启动
sched.start()

三、常见的配置

cron:在特定时间定期运行 job

兼容 unix/linux 系统 crond 格式,扩充了秒、年以及第多少周的支持,主要参数:

year(int|str) - 年,4位数

month(int|str) - 月,1-12

day(int|str) - 月,1-31

week(int|str) - 一年中的第多少周,1-53

day_of_week(int|str) - 星期,0-6 或者 mon,tue,wed,thu,fri,sat,sun

hour(int|str) - 小时,0-23

minute(int|str) - 分,0-59

second(int|str) - 秒,0-59

start_date(int|str) - 开始时间

end_date(int|str) - 结束时间

不同于 unix/linux 系统 crond 格式,添加 job 时可以忽略不必要的字段。例如, day=1, minute=20 等价于
year='*', month='*', day=1, week='*', day_of_week='*', hour='*', minute=20, second=0,意思是在每年每月第 1 天每小时的 20 分 0 秒运行。

参考:

python中APScheduler的使用详解(python3经典编程案例)


版权声明:本文为sinat_33718563原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。