ApScheduler每月指定第几天执行

ApScheduler每月指定第几天执行

  • 业务需求:
    • 若每月某天执行,当指定天大于当月最大天数时,则当月最后一天执行。例如:指定每月31日执行,那么2月份在28号执行,4、6、9、11月份在30号执行。具体闰年和平年没有细分。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Author         : Charlie ZHANG
# @Email          : [email protected]
# @Time           : 2020/7/8 17:05
# @Version        : 1.0
# @File           : common.py
# @Software       : PyCharm

from apscheduler.triggers.combining import OrTrigger
from apscheduler.triggers.cron import CronTrigger

def test_job(p1, p2, p3):
    print('hello world')


def scheduler_data(param1, param2, param3, job_id, period, begin_time, end_time, day, week, engine):
    """
    apscheduler添加任务参数
    """
    data = {
     
        'id': job_id,
        'args': [param1, param2, param2],
        'trigger': 'cron',
        'coalesce': True,  # 任务运行过程中多次被中断,重启项目后任务也会执行多次,设置coalesce=True,只会执行一次
        'timezone': 'Asia/Shanghai',  # 设置时区为东八区
        'replace_existing': True,  # 若job_id已存在,再次添加该job_id的任务,则为替换
    }
    data['func'] = test_job
    if period == 'day':
        data['hour'] = begin_time
        # seconds after the designated run time that the job is still allowed to be run
        data['misfire_grace_time'] = calculate_time(begin_time, end_time)
    elif period == 'week':
        data['day_of_week'] = f'{NUM_TO_EWEEK[week]}'
    elif period == 'month':
        if day in (29, 30):
            trigger = OrTrigger([CronTrigger(month=2, day=28), CronTrigger(month='1,3-12', day=day)])
            data['trigger'] = trigger
        elif day == 31:
            trigger = OrTrigger([CronTrigger(month=2, day=28), CronTrigger(month='4,6,9,11', day=30),
                                 CronTrigger(month='1,3,5,7,8,10,12', day=31)])
            data['trigger'] = trigger
        else:
            data['day'] = day
    return data

你可能感兴趣的:(定时任务)