python - 如何在 Python 中每 60 秒异步执行一次函数?

标签 python function asynchronous call

我想在 Python 上每 60 秒执行一次函数,但我不想同时被阻塞。

如何异步执行?

import threading
import time

def f():
    print("hello world")
    threading.Timer(3, f).start()

if __name__ == '__main__':
    f()    
    time.sleep(20)

使用此代码,函数 f 在 20 秒 time.time 内每 3 秒执行一次。 最后它给出了一个错误,我认为这是因为 threading.timer 没有被取消。

如何取消?

提前致谢!

最佳答案

你可以试试 threading.Timer 类:http://docs.python.org/library/threading.html#timer-objects .

import threading

def f(f_stop):
    # do something here ...
    if not f_stop.is_set():
        # call f() again in 60 seconds
        threading.Timer(60, f, [f_stop]).start()

f_stop = threading.Event()
# start calling f now and every 60 sec thereafter
f(f_stop)

# stop the thread when needed
#f_stop.set()

关于python - 如何在 Python 中每 60 秒异步执行一次函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2223157/

相关文章:

python - 如何在CKAN中制作定制中间件

python - Tm1 到 python 到 R

javascript 使用非内联函数

javascript - onclick 函数参数

javascript - 'Hamming' javascript 测试 (Exercism) - 匹配两个字符串之间的字母

javascript - JS 异步函数返回未定义,尽管在异步函数内调用它

python - 无法通过蓝牙读取心率服务

python - neo4j:删除事务中的节点会导致异常

javascript 变量范围 - 我该如何解决这个问题?

javascript - Observables 中的 Promise.all 等价物是什么?