You need to enable JavaScript to run this app. Python实现毫秒级暂停后定时执行代码 解决scheduler秒级延迟问题
优惠活动
大模型
产品
解决方案
定价
更多

Python实现毫秒级暂停后定时执行代码 解决scheduler秒级延迟问题

原有代码精度不足的原因
  • 你使用的标准库sched调度器依赖time.sleep的基础精度,无毫秒级时间校准机制,系统调度波动时容易出现秒级延迟
  • 原时间解析逻辑仅精确到秒,未覆盖你要求的毫秒维度计算
毫秒级精度定时实现方案(Python 3.7+ 适配)

核心逻辑:通过纳秒级时间戳计算目标执行点,采用「长时短睡+临近轮询」的方式降低睡眠误差,全程为阻塞暂停状态,不会终止脚本运行。

1. 目标时间解析函数

支持你指定的年 月 日 时 分 秒 毫秒格式,示例输入2021 2 21 22 40 00 00可直接转换为纳秒级Unix时间戳:

import time
from datetime import datetime

def parse_target(time_str: str) -> int:
    """
    解析指定格式的时间字符串为纳秒级目标时间戳
    输入格式: "年 月 日 时 分 秒 毫秒"
    """
    year, month, day, hour, minute, sec, millisec = map(int, time_str.split())
    target_dt = datetime(
        year, month, day, hour, minute, sec,
        microsecond=millisec * 1000  # 毫秒转微秒匹配datetime参数
    )
    return int(target_dt.timestamp() * 1e9)

2. 高精度等待逻辑

def wait_until(target_ns: int):
    """阻塞等待直到目标纳秒级时间点,延迟控制在1ms以内"""
    while True:
        now_ns = time.time_ns()
        remaining = target_ns - now_ns
        if remaining <= 0:
            break
        # 剩余时间大于1ms时,提前0.5ms唤醒,避免单次睡眠过久
        if remaining > 1_000_000:
            time.sleep((remaining - 500_000) / 1e9)
        # 剩余时间小于1ms时直接轮询,无睡眠

3. 完整使用示例

# 你的自定义执行函数
def myfunc():
    print("到达指定时间,执行后续代码")

# 目标时间按要求填写即可
target_time_str = "2021 2 21 22 40 00 00"
target_ns = parse_target(target_time_str)
# 触发暂停等待
wait_until(target_ns)
# 到达时间后自动执行
myfunc()
精度补充说明
  • Windows系统默认定时器粒度为15.6ms,若需进一步压缩延迟,可安装pywin32库,在等待逻辑开头调用win32api.timeBeginPeriod(1)将系统定时器粒度调整为1ms,使用后记得调用win32api.timeEndPeriod(1)恢复默认设置。
  • 等待逻辑中不要加入其他阻塞任务,否则会影响执行精度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.03 05:54:00