之前寫過一篇關(guān)于Flask+ APScheduler的文章,但和Flask關(guān)聯(lián)比較大码秉,在使用上其實不是很方便逮矛,這篇文章記錄單獨(dú)起一個定時任務(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ù)是獨(dú)立的線程執(zhí)行
except (KeyboardInterrupt, SystemExit):
# Not strictly necessary if daemonic mode is enabled but should be done if possible
scheduler.shutdown()
print('Exit The Job!')
三晋控、后臺運(yùn)行定時任務(wù)
# 假設(shè)沒有使用虛擬環(huán)境
nohup python task_manage.py &