Python线程每X分钟运行一次,除非最后一个线程仍在运行

2024-09-30 12:13:16 发布

您现在位置:Python中文网/ 问答频道 /正文

这是一个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()

Tags: falsemaindef方式codesyncam线程

热门问题