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

aF.*_*aF. 58 python asynchronous function call

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

我该如何异步进行?

import threading
import time

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

if __name__ == '__main__':
    f()    
    time.sleep(20)
Run Code Online (Sandbox Code Playgroud)

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

我该如何取消?

提前致谢!

Dav*_*ill 100

您可以尝试使用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()
Run Code Online (Sandbox Code Playgroud)

  • 你需要`.start()`定时器,我已经编辑过了. (3认同)
  • @DavidUnderhill @aF.感谢您的帮助.我遇到了同样的问题,尽管我结束了程序,但功能仍在继续运行.我的代码中``sys.exit(0)``应该放在哪里?在函数体中,或者在调用函数之后 - 在这种情况下行`f()`? (2认同)

0xf*_*xfe 7

最简单的方法是创建一个后台线程,每 60 秒运行一次。一个简单的实现是:

import time
from threading import Thread

class BackgroundTimer(Thread):   
   def run(self):
      while 1:
        time.sleep(60)
        # do something


# ... SNIP ...
# Inside your main thread
# ... SNIP ...

timer = BackgroundTimer()
timer.start()
Run Code Online (Sandbox Code Playgroud)

显然,如果“做某事”需要很长时间,那么您需要在睡眠声明中适应它。但是,60 秒是一个很好的近似值。