Python 如何将无限超时传递给 threading.Timer 的间隔参数
Python how to pass infinite timeout to threading.Timer's interval argument
我正在使用 threading.Timer
并试图将 math.inf
(+infinity) 传递给它的 interval
参数。请查看下面的示例代码和回溯以了解我的意思。
我的问题是:
- 如何将无穷大传递给
interval
输入到 Timer
?
- 旁白:这是Python中的错误吗?
- 您认为
Timer
应该能够处理 math.inf
作为 interval
参数的值吗?
示例代码
from math import inf
from threading import Timer
def call_func_later(func, timeout_sec: float = None) -> None:
"""Call the input func after some time (sec)."""
Timer(interval=timeout_sec or inf, function=func).start()
placeholder_func = lambda *args: None
call_func_later(placeholder_func)
运行 这与 Python 3.8.5 立即抛出以下回溯:
Exception in thread Thread-1:
Traceback (most recent call last):
File "/path/to/.pyenv/versions/3.8.5/lib/python3.8/threading.py", line 932, in _bootstrap_inner
self.run()
File "/path/to/.pyenv/versions/3.8.5/lib/python3.8/threading.py", line 1252, in run
self.finished.wait(self.interval)
File "/path/to/.pyenv/versions/3.8.5/lib/python3.8/threading.py", line 558, in wait
signaled = self._cond.wait(timeout)
File "/path/to/.pyenv/versions/3.8.5/lib/python3.8/threading.py", line 306, in wait
gotit = waiter.acquire(True, timeout)
OverflowError: timestamp too large to convert to C _PyTime_t
我对最大值的最佳近似是从这个答案中获得的:
# 64-bit integer, converted from nanoseconds to seconds, and subtracting 0.1
# just to be in bounds. SEE:
MAX_TIMEOUT_SEC = 2 ** 63 / 1e9 - 0.1
此值为 9,223,372,036.754776 秒,转换为 ~292 年。
因为到那时我可能已经死了,所以我将使用该值而不是 math.inf
。
我正在使用 threading.Timer
并试图将 math.inf
(+infinity) 传递给它的 interval
参数。请查看下面的示例代码和回溯以了解我的意思。
我的问题是:
- 如何将无穷大传递给
interval
输入到Timer
? - 旁白:这是Python中的错误吗?
- 您认为
Timer
应该能够处理math.inf
作为interval
参数的值吗?
- 您认为
示例代码
from math import inf
from threading import Timer
def call_func_later(func, timeout_sec: float = None) -> None:
"""Call the input func after some time (sec)."""
Timer(interval=timeout_sec or inf, function=func).start()
placeholder_func = lambda *args: None
call_func_later(placeholder_func)
运行 这与 Python 3.8.5 立即抛出以下回溯:
Exception in thread Thread-1:
Traceback (most recent call last):
File "/path/to/.pyenv/versions/3.8.5/lib/python3.8/threading.py", line 932, in _bootstrap_inner
self.run()
File "/path/to/.pyenv/versions/3.8.5/lib/python3.8/threading.py", line 1252, in run
self.finished.wait(self.interval)
File "/path/to/.pyenv/versions/3.8.5/lib/python3.8/threading.py", line 558, in wait
signaled = self._cond.wait(timeout)
File "/path/to/.pyenv/versions/3.8.5/lib/python3.8/threading.py", line 306, in wait
gotit = waiter.acquire(True, timeout)
OverflowError: timestamp too large to convert to C _PyTime_t
我对最大值的最佳近似是从这个答案中获得的:
# 64-bit integer, converted from nanoseconds to seconds, and subtracting 0.1
# just to be in bounds. SEE:
MAX_TIMEOUT_SEC = 2 ** 63 / 1e9 - 0.1
此值为 9,223,372,036.754776 秒,转换为 ~292 年。
因为到那时我可能已经死了,所以我将使用该值而不是 math.inf
。