main.py 1.1 KB

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