7

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?

4
  • No, same thread will be used Commented Feb 17, 2017 at 6:47
  • @VivekKumar - no, a new thread is created for each timer event. Timer is a subclass of Thread. Commented Feb 17, 2017 at 7:25
  • @tdelaney Ohk. I looked at docs.python.org/2/library/threading.html#threading.Timer and inferred that its a single thread which will execute repeatedly Commented Feb 17, 2017 at 8:41
  • @VivekKumar the threading.Timer instance is a single instance which represents a single thread. It can be made to run repetitive code, if the function it calls contains a loop. However, as explained in that documentation link, print_hello will only be called once by the threading.Timer object. Multiple threads are created because print_hello creates a new instance each time. Commented Oct 7, 2022 at 20:30

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Won't this fail after about 1000 iterations or so, due to Pythons recursion stack?
@kebman Not in this case. print_hello reschedules itself to be run again in the future and then returns. It didn't call itself again so it is not recursive. threading.Timer(5.0, print_hello).start() just hands the print_hello function object to the timer and says call me again in 5.
0

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.

5 Comments

Thanks for indentation. I am not sure how stackoverflow works and if I can ask follow- up questions. But, Can I achieve the same without creating new threads?
Yes.. You can continue here in the comments or edit the original post question citing: PS: OK I got this..but now m stuck here..
And you can always upvote the response which answers your question
Okay then! So is there a way to run a function periodically without creating new threads?
For parallelism you can use thread pools (group of pre-instantiated, idle threads) as described [metachris.com/2016/04/python-threadpool/] here. But for periodic execution timer threads are way to go

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.