zoukankan      html  css  js  c++  java
  • 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 &
    
  • 相关阅读:
    《C语言笔记:linux下C程序的内存映像》
    《C语言笔记:结构体内存对齐》
    《C语言笔记:一些自实现的字符串函数》
    《C语言笔记:大小端模式》
    《将博客搬至CSDN》
    《C语言笔记:三种内存来源》
    使用vue-cli3的方式创建项目并引入vant
    tomcat部署多个项目
    jenkins构建项目失败
    tomcat安装
  • 原文地址:https://www.cnblogs.com/huiwenhua/p/12592658.html
Copyright © 2011-2022 走看看