You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何设置BackgroundScheduler首次在应用启动5分钟后触发任务?

解决定时任务首次延迟5分钟执行的问题

你当前的代码中,next_run_time=datetime.time()会让任务在应用启动时立即执行,要实现首次执行在启动后5分钟,同时后续保持每日UTC13点的定时规则,可以按以下方式修改:

修改步骤

  1. 确保导入datetime和timedelta模块(如果未导入):
from datetime import datetime, timedelta
  1. 计算启动后5分钟的时间作为首次执行时间:
    替换原来的next_run_time=datetime.time(),改为基于当前时间加5分钟的带时区datetime对象,和scheduler时区保持一致:
next_run_time = datetime.now(tz=scheduler.timezone) + timedelta(minutes=5)

修改后的完整代码

from datetime import datetime, timedelta
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger

scheduler = BackgroundScheduler(timezone=app.container.config.get("app.timezone"))
job_id = random.randint(0, 999)
job_name = f"mys_fetch_background_job_{job_id}"
    
# 调度数据拉取任务,首次延迟5分钟执行
scheduler.add_job(
        my_service.fetch_data,
        CronTrigger.from_crontab(
            app.container.config.get("app.my_service.data_reload_cron_utc"), 
            # 配置值为 0 13 * * *
            "UTC",
        ),
        next_run_time=datetime.now(tz=scheduler.timezone) + timedelta(minutes=5),
        id=str(job_id),
        name=job_name
)
scheduler.start()

说明

  • 使用datetime.now(tz=scheduler.timezone)获取与调度器时区一致的当前时间,避免时区不匹配导致的执行时间偏差
  • 首次执行时间设置为当前时间加5分钟,之后任务会自动按照Cron表达式0 13 * * * UTC的规则,每日UTC时间13点执行

内容的提问来源于stack exchange,提问作者Saturnian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 02:25:17