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

如何修改Python threading.Timer实现递减定时后循环执行?

实现动态循环间隔的定时任务

原代码以固定5秒间隔重复执行showA():

import threading
import datetime

def showA():
    now = datetime.datetime.utcnow() + datetime.timedelta(hours=9)
    now_time = datetime.time(now.hour,now.minute,now.second)
    a = 'timer_checking...'
    print(f'{a} {now_time}')
    second = 5
    threading.Timer(second, showA).start()

showA()

需求:让showA()按**5秒→4秒→3秒→2秒→1秒→5秒→...**的循环间隔执行。

修改后的代码

import threading
import datetime

def showA():
    # 打印当前时间与提示信息
    now = datetime.datetime.utcnow() + datetime.timedelta(hours=9)
    now_time = datetime.time(now.hour, now.minute, now.second)
    print(f'timer_checking... {now_time}')
    
    # 初始化间隔状态(仅第一次执行时触发)
    if not hasattr(showA, 'current_interval'):
        showA.current_interval = 5
    
    # 启动下一次定时任务
    threading.Timer(showA.current_interval, showA).start()
    
    # 更新下一次执行的间隔,达到1秒后重置为5秒
    showA.current_interval -= 1
    if showA.current_interval <= 0:
        showA.current_interval = 5

showA()

关键逻辑说明

  • 用函数属性showA.current_interval保存当前间隔值,无需额外全局变量。
  • 首次执行时初始化间隔为5秒,每次启动定时器后将间隔减1。
  • 当间隔值≤0时重置为5秒,实现循环往复的间隔逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 03:45:48