Python定時任務(wù)框架APScheduler實戰(zhàn)Demo

之前寫過一篇關(guān)于Flask+ APScheduler的文章,但和Flask關(guān)聯(lián)比較大,在使用上其實不是很方便,這篇文章記錄單獨起一個定時任務(wù)服務(wù),與業(yè)務(wù)解耦合。

一、安裝APScheduler

pip install APScheduler

二、創(chuàng)建任務(wù)管理文件task_manage.py

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

# 此方法只是demo,在實際項目中可import業(yè)務(wù)方法
def test_task():
    print('test_task')

if __name__  == '__main__':

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

    # 初始化
    test_task()

    # 每半小時執(zhí)行一次
    scheduler.add_job(test_task, "interval", minutes=30)

    # 每天早晨7:00任務(wù)
    # scheduler.add_job(test_task, "cron", hour=7, minute=30)
    # 每周一早晨7:30任務(wù), 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任務(wù),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)    #其他任務(wù)是獨立的線程執(zhí)行
    except (KeyboardInterrupt, SystemExit):
        # Not strictly necessary if daemonic mode is enabled but should be done if possible
        scheduler.shutdown()
        print('Exit The Job!')

三、后臺運行定時任務(wù)

# 假設(shè)沒有使用虛擬環(huán)境
nohup python task_manage.py &
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容