首页 > 编程语言 > 详细

拿来就用的Python定时任务框架APScheduler实战Demo

时间:2020-03-29 16:55:28      阅读:77      评论:0      收藏:0      [点我收藏+]

之前写过一篇关于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 &

拿来就用的Python定时任务框架APScheduler实战Demo

原文:https://www.cnblogs.com/huiwenhua/p/12592658.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!