APScheduler-调度器 BackgroundScheduler

当你有主程序需要执行,让定时任务在后台执行时,可以用BackgroundScheduler

python 复制代码
from apscheduler.schedulers.background import BackgroundScheduler  
import time  
  
  
# 仅运行定时任务  
scheduler = BackgroundScheduler()  
  
  
# interval example, 间隔执行, 每10秒执行一次  
def task1(x):  
    print(f'task 1 executed  {x}--------', time.time())  
  
  
# 添加一个定时任务  
scheduler.add_job(  
    task1, 'interval', seconds=10,  
    args=["xxxx"], id="task_1", replace_existing=True  
)  
  
  
# cron examples, 每5秒执行一次 相当于interval 间隔调度中seconds = 5  
def task2(y):  
    print(f'task 2 executed  {y}--------', time.time())  
  
  
# 添加一个定时任务  
scheduler.add_job(  
    task2, 'cron', second='*/5',  
    args=["yyy"], id="task_2", replace_existing=True  
)  
  
scheduler.start()  
  
while(True):  
    print('main ---------------')  
    time.sleep(1)

执行结果

复制代码
main ---------------
main ---------------
main ---------------
main ---------------
task 2 executed  yyy-------- 1698211520.0085256
main ---------------
main ---------------

Flask-APScheduler 中默认使用的就是 BackgroundScheduler

相关推荐
copyer_xyf7 分钟前
Python 类全面总结
前端·后端·python
copyer_xyf11 分钟前
Python 类型注解:从 TypeScript 迁移理解
前端·后端·python
276695829211 分钟前
谷歌google cookie逆向角度分析
开发语言·python·google·sgss·谷歌搜索·sg-ss·谷歌cookie逆向
copyer_xyf18 分钟前
Python 函数全面总结
前端·后端·python
zmzb010319 分钟前
Python课后习题训练记录Day123
开发语言·python
PersistJiao21 分钟前
python环境下免费、专业的中英翻译
开发语言·windows·python·机器翻译
hujinyuan2016036 分钟前
中国电子学会青少年软件编程(Python)(二级)等级考试试卷-真题+答案(2026年3月)
python·机器人
老毛肚38 分钟前
记一次逆向
开发语言·python
星恒随风1 小时前
Python 基础语法详解(3):顺序语句、条件语句和循环语句一篇讲清楚
开发语言·笔记·python·学习