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

相关推荐
创世宇图35 分钟前
【Python工程化实战】Kubernetes 中 Python 应用的优雅启停与健康检查:零停机滚动更新实战
python·云原生·kubernetes·优雅停机
zhiSiBuYu05171 小时前
重排序(Rerank)提升检索准确率实战指南
开发语言·python·算法
MageGojo1 小时前
集成企业工商信息查询API:从在线调试到生产级调用实战
python·调试·rest api·api集成·企业信息查询
huangjiazhi_1 小时前
Python3.14编写文件服务器
python
郭梧悠2 小时前
算法:有效的括号
python·算法·leetcode
佛珠散了一地2 小时前
ONNX Runtime GPU 推理配置指南
python
派葛穆2 小时前
Python-pip切换镜像源
开发语言·python·pip
CTA终结者2 小时前
2026年AI量化提效,工具重点要按阶段调整
人工智能·python
xxie1237943 小时前
Python 闭包:函数嵌套的 “状态捕获” 机制
开发语言·python
c_lb72883 小时前
最新AI量化提效,交易认知和技术实现要接上
人工智能·python