【发布时间】:2018-02-14 07:49:04
【问题描述】:
TL;DR threading.Timer 使用系统时间,但是在我使用它时时间会发生变化,我怎样才能让它使用系统正常运行时间?
我有一个 Python 脚本,它做了很多事情,其中之一就是设置系统时间。当这个脚本启动的时候是错误的。此脚本还需要有 30 秒的全局超时。
我一直在使用以下超时类:
class Timeout(object):
def __init__(self, seconds=1, signum=signal.SIGUSR1, exception=TimeoutException):
self.exception = exception
self.pid = os.getpid()
self.signum = signum
self.timer = threading.Timer(seconds, self.exit_function)
def exit_function(self):
os.kill(self.pid, self.signum)
def handle_timeout(self, signum, frame):
raise self.exception()
def __enter__(self):
signal.signal(self.signum, self.handle_timeout)
self.timer.start()
def __exit__(self, type, value, traceback):
self.timer.cancel()
这包含了我的整个脚本:
with Timeout(seconds=30):
main()
有时脚本会很快失败,或者在 30 秒后永远不会被杀死。我相信这是因为threading.Timer 使用了在脚本运行时更改的系统时间。无论如何我可以让它使用系统正常运行时间吗?
【问题讨论】:
-
不是重复的,所有这些示例也使用系统时间,我想使用系统正常运行时间,例如
/proc/uptime -
threading.Timer是基于条件锁的,基于一个单调计时器,它说:时钟不受系统时钟更新的影响。所以这不是你的问题。您不需要系统正常运行时间 - 您已经拥有独立的时间 -
嗯,我正在运行
Debian Linux 3.10.103-marvell armv7l GNU/Linux和 Python 2.7.9。如果我更改时间,它会影响threading.Timer内部的Event.interval调用。 -
是的,刚刚发现你可能有 python