【问题标题】:Start one function repeatedly while another function is executed [duplicate]在执行另一个功能时重复启动一个功能[重复]
【发布时间】:2016-06-08 22:15:30
【问题描述】:

我有一个需要很长时间才能完成的功能。如何在执行长函数时每 X 秒执行另一个函数?

脚本使用 Python 3.4

【问题讨论】:

  • 你应该看看 Python 的 threading 和/或 multiprocessing。您需要在单独的线程/进程中执行耗时功能。或者你在主线程中保留长时间的功能,并使用timer 每 x 秒启动一次“其他”功能。
  • 经过这两个骗子,你可以做到。

标签: python python-3.x asynchronous


【解决方案1】:

这是一个非常简单的例子。如果在第一个功能完成后终止第二个功能对您很重要,仍然可以对其进行调整。

import threading, time

def func_long(ev):
    # do stuff here
    for _ in range(12):
        print("Long func still working")
        time.sleep(1)

    # if complete
    ev.set()

def run_func(ev, nsec):
    if ev.is_set():
        return
    print ("Here run periodical stuff")
    threading.Timer(nsec, run_func, [ev, nsec]).start()

def main():
    ev = threading.Event()
    threading.Timer(5.0, run_func, [ev, 5]).start()
    func_long(ev)

if __name__=='__main__':
    main()

【讨论】:

    猜你喜欢
    • 2013-09-12
    • 1970-01-01
    • 1970-01-01
    • 2020-12-15
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多