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

如何优化每5分钟第2秒触发循环的Python代码实现

优化实现方案

核心优化思路

  • 你需要的触发规则是分钟数为5的整数倍、秒数等于2,直接用取模运算now.minute % 5 == 0就可以替代原代码中十多行的or判断,逻辑完全等价,代码更简洁。
  • 原代码内层while属于冗余写法,触发后固定sleep300秒的方案容易因为任务执行耗时、系统调度出现时间漂移。

改动最小的优化版本

这个版本仅修改判断条件,保留原有使用习惯,改动成本最低:

import datetime
import time

def time_now():
    now = datetime.datetime.now()
    current_time = now.strftime("%H:%M:%S")
    print("Current Time =", current_time)

while True:
    now = datetime.datetime.now()
    # 一行替代原多段or判断,逻辑完全等价
    if now.minute % 5 == 0 and now.second == 2:
        time_now()
        print('Something')
        # 避免同一秒内重复触发
        time.sleep(1)
    # 每次循环休眠100毫秒,降低CPU空转占用
    time.sleep(0.1)

更高精度低占用版本

这个版本通过动态计算下一次触发的等待时间,完全避免无效轮询,CPU占用几乎为0,触发时间精度更高:

import datetime
import time

def time_now():
    now = datetime.datetime.now()
    current_time = now.strftime("%H:%M:%S")
    print("Current Time =", current_time)

while True:
    now = datetime.datetime.now()
    minute_mod = now.minute % 5
    # 计算到下一个触发点的等待秒数
    if minute_mod == 0:
        if now.second <= 2:
            wait_seconds = 2 - now.second
        else:
            wait_seconds = 300 - now.second + 2
    else:
        wait_seconds = (5 - minute_mod) * 60 - now.second + 2
    # 直接睡到触发点再执行逻辑
    time.sleep(wait_seconds)
    time_now()
    print('Something')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 16:45:02