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

相关推荐
JHC0000005 小时前
基于Ollama,Milvus构建的建议知识检索系统
人工智能·python·milvus
mOok ONSC5 小时前
SpringBoot项目中读取resource目录下的文件(六种方法)
spring boot·python·pycharm
GIS兵墩墩6 小时前
postgis--PostgreSQL16及其plpython3u扩展
python·postgis
new Object ~6 小时前
LangChain的短期记忆存储实现
python·langchain
魔都吴所谓6 小时前
【Python】从零构建:IP地理位置查询实战指南
开发语言·python·tcp/ip
测试19986 小时前
使用Python自动化生成接口测试用例
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·接口测试
智算菩萨7 小时前
【Pygame】第10章 游戏状态管理与场景切换机制
python·游戏·pygame
songcream17 小时前
TensorFlow的一些基本概念
人工智能·python·tensorflow
AI逐月8 小时前
解决 ComfyUI 插件安装后 Nanobind 报错问题:soxr 版本冲突原理解读
开发语言·python