python - 确保任意代码需要 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 分钟返回。
解决方案
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())
,为了简单起见,我把它分开了。
推荐阅读
- c++ - 为什么公共重载与某些编译器上的私有 using 指令冲突?
- java - 从 JDBC 触发 SQL 命令时出错 - java.sql.SQLSyntaxErrorException
- javascript - 从下拉列表中选择正确的图像
- javascript - Invariant Violation Invalid hook call 部署错误
- python - Python给出AttributeError:'PngImageFile'对象没有带有Pillow的'read'属性
- java - 如何使用 RestTemplate 发布 bean 列表,但 bean 必须是字节数组?
- javascript - Ajv 响应编号为字符串,带有 coerceTypes: true
- asynchronous - 当在同一个 React 块中使用不同的线程调度程序时会发生什么?
- python - 如何根据两个值对字典进行分组?
- ansible - 查找给定文件的 Yaml 脚本是否为空