【发布时间】:2021-01-29 12:33:30
【问题描述】:
在我的外围设备中,我使用 python Timer:
timer = Timer(45, my_func, [])
timer.start()
问题是在定时器运行过程中,设备时区可以更改(由于设备连接到WIFI),定时器会立即停止。
是否存在另一种对时区变化不敏感的方式?
我使用 Python 3.7.3
【问题讨论】:
在我的外围设备中,我使用 python Timer:
timer = Timer(45, my_func, [])
timer.start()
问题是在定时器运行过程中,设备时区可以更改(由于设备连接到WIFI),定时器会立即停止。
是否存在另一种对时区变化不敏感的方式?
我使用 Python 3.7.3
【问题讨论】:
你可以用一个定时器来包装你的函数,并且只使用普通的线程。
示例代码:
from threading import Thread
import time
def wrapper_func(seconds: float, func, args: dict, sleep_interval_seconds: float = 0.1):
seconds_left = seconds
while seconds_left >= 0:
time.sleep(sleep_interval_seconds)
seconds_left -= sleep_interval_seconds
if args:
func(**args)
else:
func()
def timed_thread(seconds: float, target, func_args: dict = None) -> Thread:
return Thread(target=wrapper_func, args=(seconds, target, func_args))
def funcc():
print("BBBBBB")
t = timed_thread(3, funcc)
t.start()
print("AAAAA")
time.sleep(4)
print("CCCCC")
将打印:
AAAAA
BBBBBB
CCCCC
【讨论】: