Run a python function every second

后端 未结 6 864
我寻月下人不归
我寻月下人不归 2020-12-16 08:08

What I want is to be able to run a function every second, irrelevant of how long the function takes (it should always be under a second). I\'ve considered a number of option

6条回答
  •  醉话见心
    2020-12-16 08:49

    The approach using a threading.Timer (see code below) should in fact not be used, as a new thread is launched at every interval and this loop can never be stopped cleanly.

    # as seen here: https://stackoverflow.com/a/3393759/1025391
    def update(i):
      threading.Timer(1, update, [i+1]).start()
      # business logic here
    

    If you want a background loop it is better to launch a new thread that runs a loop as described in the other answer. Which is able to receive a stop signal, s.t. you can join() the thread eventually.

    This related answer seems to be a great starting point to implement this.

提交回复
热议问题