这是一个3.x python程序。为web服务器创建了一个线程-没有问题
在一个线程中运行另一个函数,我希望每X秒运行一次,除非前面的线程仍在运行,在这种情况下,我们可以跳过这个迭代。我不希望在上一次跑步结束和新一次跑步开始之间有X秒的休息
期望的行为:
X=180秒(3分钟)
8:00 am - Code begins
8:01 am - Code completes
8:03 am - Code begins
8:07 am - Code completes (we skipped the 8:06 am run)
8:09 am - Code begins
下面的代码每X秒运行一次函数(main),但不检查是否已经有先前的线程在运行
def sync():
t_sync = threading.Timer(syncInterval, sync)
t_sync.daemon = False
t_sync.start()
main()
实现这一目标的最佳方式是什么
多亏了PygoNode关于is_live()的想法,我才得以完成以下工作。这可能不是最优雅的方式,但它确实有效
def sync():
t_sync = threading.Thread(target=main)
t_sync.daemon = False
t_sync.start()
while True:
time.sleep (syncInterval)
if t_sync.is_alive():
logger.warning ('Sync: Prior thread still running. Do not kick off another sync.')
else:
t_sync = threading.Thread(target=main)
t_sync.daemon = False
t_sync.start()
Timer有一个is_alive()方法。您可以重构
sync()
方法,以在启动后返回线程,然后将该引用传递给下一个sync()
调用检查,以确定现有方法是否仍然有效/正在运行相关问题 更多 >
编程相关推荐