Threading.Timer(5, function) launch every 5 second

天涯浪子 提交于 2019-12-25 08:49:45

问题


I'm having a hard hard time with Timer function from threading.

Basically, when my program starts, I want to log stats every x second.

So I thought I could do it with the Timer function (launch function every 5 second).

For now, I did :

from threading import Timer
def startLogger():
    while True:
        t = Timer(5, function)
        t.start()


def function():
    print("hey")

But it launch error, so I think it's not the good way to do it.

RuntimeError: can't start new thread

If someone can give me a clue, it would be appreciated!


回答1:


You can try the following. The idea is, that you are scheduling the next function call just at the end of this function's body:

import threading

def mylog():
  print "hey"
` threading.Timer(5.0, mylog)`.start()

mylog()



回答2:


Instead of starting a new thread every five seconds, you can create just one thread and run all your code from there.

from time import sleep
from threading import Thread

def startLogger():
    while True:
        function()
        sleep(5)

def function():
    print("hey")

Thread(target=startLogger).start()

startLogger will continually run. It'll call function, then pause for 5 seconds, then start again, calling function and so on.

It goes in its own thread so that the sleep(5) doesn't also stop your main thread for 5 seconds.



来源:https://stackoverflow.com/questions/45684451/threading-timer5-function-launch-every-5-second

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!