flask_apscheduler 封装应用

安稳与你 提交于 2020-02-21 18:13:02

flask_apscheduler 封装应用

一、 常规初始化

# extensions.py
from flask_apscheduler import APScheduler
scheduler = APScheduler()
# app.py
import atexit
import fcntl
import pathlib
from flask import Flask
from ..extensions import scheduler
from lib.schedulers.scheduler import SchedulerInitialization

_default_instance_path = pathlib.Path(__file__).parents[0].joinpath('instance')


def create_app():
    app = Flask(__name__, instance_relative_config=True, instance_path=_default_instance_path)
    app.secret_key = 'A0r98j/3X-^R~H!j#_mN]L@*W/,?T'
    configure_scheduler(app)
    return app

def configure_scheduler(app):
    file_path = "../lib/schedulers/scheduler.lock"
    # 确保多进程下的定时任务初始化一次
    f = open(file_path, "wb")
    try:
        fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
        scheduler.init_app(app)
        SchedulerInitialization(app)
        scheduler.start()
    except:
        fcntl.flock(f, fcntl.LOCK_UN)

    @atexit.register
    def unlock():
        fcntl.flock(f, fcntl.LOCK_UN)
        f.close()

二、自定义封装

import datetime
import logging
import pathlib
from ..logs.logger import log

class SchedulerInitialization:

    def __init__(self, app=None):
        self.app = None
        self.scheduler = None
        if app:
            self.sch_init(app)

    def sch_init(self, app):
        self.app = app
        self.scheduler = app.apscheduler
        self.sch_date()
        self.sch_cron()
        self._log_handler()

    def _log_handler(self):
        # 定时日志记录
        log = logging.getLogger('apscheduler')
        log.setLevel(20)
        logs_path = pathlib.Path(__file__).resolve().parent.joinpath('scheduler.log')
        log_handler = logging.FileHandler(filename=logs_path, encoding='utf-8')
        fmt = logging.Formatter('%(asctime)s - %(levelname)s:%(name)s:%(message)s')
        log_handler.setFormatter(fmt)
        log.addHandler(log_handler)

    def sch_date(self):
        trigger = 'date'
        self._add_jobs(date_example, 'date_example', trigger=trigger,
                       run_date=datetime.datetime.now() + datetime.timedelta(seconds=5))

    def sch_cron(self):
        trigger = 'cron'
        self._add_jobs(per_hour_example, 'per_hour_example', trigger=trigger, hour='*')
        self._add_jobs(cron_example, 'cron_example', trigger=trigger, hour=0, minute=0, second=5,args=['args'])
        self._add_jobs(per_10_seconds, 'per_10_seconds', trigger=trigger, second='0/10')

    def _add_jobs(self, func, _id, trigger, **kwargs):
        kwargs_dic = {'call_func': func}
        if 'kwargs' in kwargs:
            kwargs_dic.update(kwargs['kwargs'])
            
        # 项目重启不立刻执行
        self.scheduler.add_job(func=self._func, id=_id, trigger=trigger,
                               kwargs=kwargs_dic, **kwargs)
        # 项目开始即可执行
        # self.scheduler.add_job(func=self._func, id=_id, trigger=trigger, next_run_time=datetime.datetime.now(),
        #                        kwargs=kwargs_dic, **kwargs)

    def _func(self, *args, **kwargs):
        call_func = kwargs['call_func']
        kwargs.pop('call_func')
        try:
            self.scheduler.app.app_context().push()
            res = call_func(*args, **kwargs)
            return res
        except Exception as e:
            log.error(e)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!