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?

Asked By: Praniti Gupta

||

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.

Answered By: Priyank Mehta

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.

Answered By: tdelaney

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().

Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.