| 123456789101112131415161718192021222324252627282930313233343536373839404142434445 |
- # -*- coding: utf-8 -*-
- '''
- 全局定时
- 例子
- scheduler.add_job(midnight_task, 'cron', hour=0, minute=0) # 每天定时执行
- scheduler.add_job(test_error, 'interval', seconds=2) # 循环间隔多少秒执行
- scheduler.add_job(weekly_task, 'cron', day_of_week='mon,wed,sat', hour=22, minute=30) # 添加定时任务,设置为每周一、三、六晚上10点30分执行
- '''
- from apscheduler.schedulers.background import BackgroundScheduler
- import time
- def hello_world():
- print("Hello World")
- def hello_kitty():
- print("Hello Kitty")
- def test_error():
- try:
- a = 1 / 0
- except ZeroDivisionError:
- print("Division by zero")
- # 创建 BackgroundScheduler 实例
- scheduler = BackgroundScheduler()
- # 添加定时任务
- scheduler.add_job(hello_world, 'interval', seconds=10)
- scheduler.add_job(hello_kitty, 'interval', seconds=15)
- scheduler.add_job(test_error, 'interval', seconds=2)
- # 启动调度器
- scheduler.start()
- # 为了防止程序退出,这里使用一个无限循环
- try:
- while True:
- time.sleep(1)
- except (KeyboardInterrupt, SystemExit):
- # 关闭调度器
- scheduler.shutdown()
|