繁体   English   中英

Python中如何做周期性任务

[英]How to do periodic tasks in Python

我想在 Python 中每隔几秒运行一次 function。 function 执行需要一些时间,我也想将其包括在等待时间中。

我不想这样做,因为它不是每 2 秒严格执行一次,并且会破坏周期性(my_function 也需要时间来执行。)

while True:
    time.sleep(2)
    my_function()

我也不想这样做,因为它在 Thread-2 的 while 循环上使用了太多的 CPU。

# Thread-1
While True:
    time.sleep(2)
    event.set()

# Thread-2
While True:
    if event.is_set():
        my_function()
    else:
        pass 

谁能帮帮我吗?

我相信日程模块是你的朋友

你可以考虑ischedule 它开箱即用地处理函数执行时间,并且不会因忙等待而浪费 CPU 时间。 您可以使用:

from ischedule import schedule, run_loop

schedule(my_function, interval=2)
run_loop()

如果我正确理解了您的问题,我发现此代码运行良好。

代码分解:

  • 运行 func1
  • 运行 func2
  • 等待 2s
  • 之后做其他事情
  • 等待 1s
  • 再做一遍
import threading
import time

def func1():
    print("function 1 has been called")

def func2():
    print("function 2 has been called")

def loop():
    print("loop print 1")
    thread = threading.Thread(target=func1, name="thread")
    thread.start()

    while thread.is_alive():
        continue

    if not thread.is_alive():
        thread2 = threading.Thread(target=func2, name="thread2")
        thread2.start()

    while thread2.is_alive():
        continue
    
    time.sleep(2)

while True:
    loop()
    print("Some other thing")
    time.sleep(1)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM