gpt4 book ai didi

python - 如何在Python中每X分钟调用后台线程中的特定方法?

转载 作者:行者123 更新时间:2023-12-01 05:28:26 24 4
gpt4 key购买 nike

如何在 Python 中编写一个后台线程,该线程将每隔几分钟调用一个特定的方法。

比方说,如果我第一次启动我的程序,那么它应该立即调用该方法,之后,它应该每隔 X 分钟继续调用该方法?

可以用Python实现吗?

我对 Python 线程没有太多经验。在 Java 中,我可以使用 TimerTaskScheduledExecutors 来解决这个问题,但不确定如何使用 Python 来实现?

在 Python 中执行此操作的最佳方法是什么?

最佳答案

使用threading.Timer .

例如:

import threading

def print_hello():
print('Hello')
timer = threading.Timer(2, print_hello) # # Call `print_hello` in 2 seconds.
timer.start()

print_hello()

关于python - 如何在Python中每X分钟调用后台线程中的特定方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20866003/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com