首页 > 解决方案 > 确保任意代码需要 15 分钟才能运行

问题描述

我需要执行此操作的代码:

def foo():
  now = datetime.datetime.utcnow()

  # Some code will run that takes a variable amount of time
  # (less than 15 minutes)

  # This code should run no sooner than 15 minutes after `now`

请注意,这使用time.sleep! time.sleep会停止整个过程,但我需要进行计算foo()foo()在开始后不早于 15 分钟返回。

标签: pythonwait

解决方案


datetime不需要,因为我们不需要用人类时钟(小时、分钟、秒)来思考。

我们所需要的只是自过去任何固定时刻以来的几秒钟,而time.monotonic正是这样做的。

import time

DELAY = 900  # in seconds

start = time.monotonic()
# computation here
end = time.monotonic()
duration = end - start
time.sleep(DELAY - duration)

最后三行可以写成time.sleep(start + DELAY - time.monotonic()),为了简单起见,我把它分开了。


推荐阅读