How threading.timer works in python
Question:
I want to run a function every n
seconds. After some research, I figured out this code:
import threading
def print_hello():
threading.Timer(5.0, print_hello).start()
print("hello")
print_hello()
Will a new thread be created every 5 sec when print_hello()
is called?
Answers:
Little indentation of code would help to better understand the question.
Formatted Code:
from threading import Timer
def print_hello():
Timer(5.0,print_hello,[]).start()
print "Hello"
print_hello()
This code works spawning a new thread every 5 sec as you are calling it recursively in every new thread call.
Timer
is a thread. Its created when you instantiate Timer()
. That thread waits the given amount of time then calls the function. Since the function creates a new timer, yes, it is called every 5 seconds.
In my case this worked
import turtle
def hello:
threading.Timer(2, hello()).start()
hello()
hello function should contain braces while passing as an argument in Timer().
I want to run a function every n
seconds. After some research, I figured out this code:
import threading
def print_hello():
threading.Timer(5.0, print_hello).start()
print("hello")
print_hello()
Will a new thread be created every 5 sec when print_hello()
is called?
Little indentation of code would help to better understand the question.
Formatted Code:
from threading import Timer
def print_hello():
Timer(5.0,print_hello,[]).start()
print "Hello"
print_hello()
This code works spawning a new thread every 5 sec as you are calling it recursively in every new thread call.
Timer
is a thread. Its created when you instantiate Timer()
. That thread waits the given amount of time then calls the function. Since the function creates a new timer, yes, it is called every 5 seconds.
In my case this worked
import turtle
def hello:
threading.Timer(2, hello()).start()
hello()
hello function should contain braces while passing as an argument in Timer().