How can I start this timer forever?

from threading import Timer def hello(): print "hello, world" t = Timer(30.0, hello) t.start() 

This code starts only one timer.

How can I start the timer forever?

Thanks,

updated

it is right:

 import time,sys def hello(): while True: print "Hello, Word!" sys.stdout.flush() time.sleep(2.0) hello() 

and this:

 from threading import Timer def hello(): print "hello, world" sys.stdout.flush() t = Timer(2.0, hello) t.start() t = Timer(2.0, hello) t.start() 
+4
source share
3 answers

A threading.Timer executes a function once. This function can "work forever" if you want, for example:

 import time def hello(): while True: print "Hello, Word!" time.sleep(30.0) 

Using multiple instances of Timer will require significant resources without real added value. If you want to be non-invasive for a function that you repeat every 30 seconds, an easy way:

 import time def makerepeater(delay, fun, *a, **k): def wrapper(*a, **k): while True: fun(*a, **k) time.sleep(delay) return wrapper 

and then schedule makerepeater(30, hello) instead of hello .

For more complex operations, I recommend the standard sched library module.

+9
source

Just restart (or recreate) the timer inside the function:

 #!/usr/bin/python from threading import Timer def hello(): print "hello, world" t = Timer(2.0, hello) t.start() t = Timer(2.0, hello) t.start() 
+8
source

from threading import Timer it depends on what part you want to run forever, if it creates a new thread, say every 10 seconds, you can do the following from a thread import Timer

 import time def hello(): print "hello, world" while True: #Runs the code forever over and over again, called a loop time.sleep(10)#Make it sleep 10 seconds, as to not create too many threads t = Timer(30.0, hello) t.start() 

If this is a hello world that you want to run forever, you can do the following:

 from threading import Timer def hello(): while True: # Runs this part forever print "hello, world" t = Timer(30.0, hello) t.start() 

Search loops in python for more info on this

+1
source

Source: https://habr.com/ru/post/1307849/


All Articles