从特定的挂钟时间开始,每5分钟运行一次函数



我想从特定的挂钟时间开始,每5分钟运行一次函数。

我已经实现了每5分钟(间隔(运行一次的threading.timer,但我不知道如何在特定时间启动这个定时器。

from threading import Timer

class BSOJobScheduler(object):
def __init__(self, interval, function, *args, **kwargs):
self._timer = None
self.interval = interval
self.function = function
self.args = args
self.kwargs = kwargs
self.is_running = False
self.start()
def _run(self):
self.is_running = False
self.start()
self.function(*self.args, **self.kwargs)
def start(self):
if not self.is_running:
self._timer = Timer(self.interval, self._run)
self._timer.daemon = True
self._timer.start()
self.is_running = True
def stop(self):
self._timer.cancel()
self.is_running = False

请告知

最简单的方法是使用Time.Time((,所以我将使用它。

你这样启动计时器:start = Time.time()最后是这样的:end = Time.time()然后,为了得到时间值,你只需要从end中减去start,如下所示:value = end - start你必须这样做,因为start = Time.time()从计算机中获取值,所以你的下一步是从计算机end = Time.time()中获取另一个值,然后减去它

您只需检查value>=300(300秒等于5分钟(。

其中一个线程可以执行以下操作:

INTERVAL = 5 * 60
next_run = time.monotonic() # better than time.time()
while True:                 # or while not stop_condition:
my_function()           # should not take more time than the INTERVAL
next_run += INTERVAL
sleep_time = next_run - time.monotonic()
time.sleep(sleep_time)

最新更新