Python定时任务框架APScheduler实战Demo

之前写过一篇关于Flask+ APScheduler的文章,但和Flask关联比较大,在使用上其实不是很方便,这篇文章记录单独起一个定时任务服务,与业务解耦合。

一、安装APScheduler

pip install APScheduler

二、创建任务管理文件task_manage.py

# -*- coding: utf-8 -*-
'''
# Created on 2020-03-29
# 任务管理
# @author: 程好玩
'''
from apscheduler.schedulers.background import BackgroundScheduler
import os, time

# 此方法只是demo,在实际项目中可import业务方法
def test_task():
    print('test_task')

if __name__  == '__main__':

    scheduler = BackgroundScheduler(timezone='Asia/Shanghai')

    # 初始化
    test_task()

    # 每半小时执行一次
    scheduler.add_job(test_task, "interval", minutes=30)

    # 每天早晨7:00任务
    # scheduler.add_job(test_task, "cron", hour=7, minute=30)
    # 每周一早晨7:30任务, day_of_week:(0~6 or  mon,tue,wed,thu,fri,sat,sun)
    # scheduler.add_job(test_task, "cron", day_of_week= 0, hour=7, minute=30)
    # 每月1日早晨8:00任务,day:(1-31)
    # scheduler.add_job(test_task, "cron", day=1, hour=8, minute=0)
    scheduler.start()
    print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))

    try:
        # This is here to simulate application activity (which keeps the main thread alive).
        while True:
            time.sleep(2)    #其他任务是独立的线程执行
    except (KeyboardInterrupt, SystemExit):
        # Not strictly necessary if daemonic mode is enabled but should be done if possible
        scheduler.shutdown()
        print('Exit The Job!')

三、后台运行定时任务

# 假设没有使用虚拟环境
nohup python task_manage.py &
posted @ 2020-03-29 15:46  程会玩  阅读(669)  评论(0编辑  收藏  举报