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

相关推荐
Brian Xia5 分钟前
从 0 开始手写 AI Agent 框架:nano-agentscope(二)框架搭建
人工智能·python·ai
写代码的【黑咖啡】15 分钟前
深入了解 Python 中的 Scikit-learn:机器学习的强大工具
python·机器学习·scikit-learn
逆境清醒42 分钟前
python教程总目录(更新中ing。。。)
开发语言·python
小北方城市网1 小时前
GEO 智变新篇:质效双升 + 责任共生,打造 AI 时代本地商业长效增长引擎
大数据·人工智能·python·数据库架构
Hello_wshuo1 小时前
锅炉温控系统优化
linux·python·物联网
weixin_470740361 小时前
python生成环境部署
开发语言·python
piaopiaolanghua1 小时前
Python中的SGP4轨道预报库
python·sgp4
Eiceblue1 小时前
Python 实现 CSV 转 TXT 格式 (单文件 + 批量处理)
开发语言·python·visual studio code
Iridescent11211 小时前
Iridescent:Day49
python
曲幽1 小时前
从安装到上线:一份 Nginx 实战指南,让你的 Web 应用稳建安全
python·nginx·flask·fastapi·web·gunicorn·uvicorn