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

Python运行Flask服务时如何实现每24小时稳定定时调用指定函数?

定时执行间隔异常问题修复方案

问题核心原因

  • 你部署项目使用的Replit免费实例存在休眠机制:长时间无外部访问时实例会被冻结,有新访问时实例会重启,每次重启都会重新启动func线程,线程启动后会立刻执行一次backend.get_details(),不需要等待24小时,这是出现异常短间隔的核心原因
  • 未做异常捕获:如果backend.get_details()执行过程中抛出异常,会直接跳过后续的time.sleep进入下一次循环,导致执行间隔大幅缩短
  • Flask调试模式默认开启多进程:如果你的Flask服务开启了debug模式,启动时会生成两个进程,每个进程都会单独启动一个func线程,相当于同时有两个定时任务在跑,执行次数翻倍

修复方案

1. 增加执行时间持久化校验,避免重启导致的重复执行

将上次成功执行的时间存入数据库或本地文件,每次线程启动、执行任务前先判断是否满足24小时间隔要求,不满足则先补足睡眠时间再执行:

import datetime
import time

def func():
    # 从持久化存储读取上次执行时间,首次运行可设为很久之前的时间
    def get_last_run():
        # 此处替换为你自己的读取逻辑,比如读数据库或者本地json文件
        try:
            with open("last_run.txt", "r") as f:
                return datetime.datetime.fromisoformat(f.read())
        except:
            return datetime.datetime.now() - datetime.timedelta(days=1)
    
    def save_last_run(run_time):
        # 此处替换为你自己的存储逻辑
        with open("last_run.txt", "w") as f:
            f.write(run_time.isoformat())

    last_run_time = get_last_run()
    while True:
        now = datetime.datetime.now()
        interval = (now - last_run_time).total_seconds()
        # 未到24小时先睡够间隔
        if interval < 86400:
            time.sleep(86400 - interval)
        
        # 加异常捕获,避免报错跳过sleep
        try:
            backend.get_details()
            last_run_time = datetime.datetime.now()
            save_last_run(last_run_time)
        except Exception as e:
            # 可自行添加错误日志打印逻辑
            pass
        
        # 执行完成后等待24小时进入下一轮
        time.sleep(86400)

2. 关闭Flask调试模式,避免多进程重复启动线程

修改Flask启动代码,关闭debug参数:

def run():
    # 关闭debug模式,禁止自动重载生成多进程
    app.run(host="0.0.0.0", port=8000, debug=False)

如果必须开启debug模式做开发,需要修改启动逻辑,只在主进程启动定时线程:

import os

if __name__ == '__main__':
    # 只在Flask主进程启动定时线程,跳过重载进程
    if not app.debug or os.environ.get("WERKZEUG_RUN_MAIN") == "true":
        keep_alive()
    run()

3. 可选:Replit实例保活

如果需要保证实例24小时运行不被休眠,可以用外部定时服务每隔5-10分钟访问一次你的Flask服务地址,避免实例被冻结,保证定时任务稳定执行。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 02:36:04