定时任务
ASPscheduler
pyproject.toml
[tool.poetry.dependencies]
python = "^3.9"
apscheduler = "^3.10.4"
python
from apscheduler.schedulers.blocking import BlockingScheduler
from datetime import datetime, timedelta
def sch_test(job_type):
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print('时间:{}, {}测试apscheduler'.format(now, job_type))
task = BlockingScheduler(timezone="Asia/Shanghai")
task.add_job(func=sch_test, args=('一次性任务',),trigger='date', next_run_time=datetime.now() + timedelta(seconds=3))
task.add_job(func=sch_test, args=('定时任务',), trigger='cron', second='*/5')
task.add_job(func=sch_test, args=('定时任务',), trigger='interval', hours=1)
task.add_job(func=sch_test, args=('定时任务',), trigger='cron', second='*/5', jitter=30, misfire_grace_time=60)
task.add_job(func=sch_test, args=('循环任务',), trigger='interval', seconds=3)
task.start()
schedule
shell
pip install schedule
python
import schedule
import time
import traceback
def make_loop(job, minutes=None, hours=None):
job()
if minutes or hours:
if minutes:
schedule.every(minutes).minutes.do(job)
elif hours:
schedule.every(hours).hours.do(job)
while True:
schedule.run_pending()
time.sleep(5)
def test():
print('test')
def job():
try:
test()
except:
traceback.print_exc()
make_loop(job, minutes=1) # 每1分钟执行一次