Threading.Timer - Repeat Function Every 'N' Seconds

threading.Timer - repeat function every 'n' seconds

The best way is to start the timer thread once. Inside your timer thread you'd code the following

class MyThread(Thread):
def __init__(self, event):
Thread.__init__(self)
self.stopped = event

def run(self):
while not self.stopped.wait(0.5):
print("my thread")
# call a function

In the code that started the timer, you can then set the stopped event to stop the timer.

stopFlag = Event()
thread = MyThread(stopFlag)
thread.start()
# this will stop the timer
stopFlag.set()

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

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

Repeating a function in a background thread every N seconds

Short answer :

Don't override start(). Override run() instead.

Long answer because you're asking for details :

With the class definition in your first snippet, you've created a class which inherits from Thread, however you've overriden the start() method supposed to start your thread by a new method which is looping until the stop_event is set, that is to say, the method supposed to actually start your thread doesn't do this anymore.

So, when you try to start your thread, you actually run the loop calling your callback function in your current and only thread. And since it's an infinite loop, your second "thread" is not started, and you have no way to "stop" it.

You mustn't override start (well not in this way). Instead, override the run method. This is the method that will be run by your thread when you start it.

Also, you should do super().__init__() instead of Thread.__init__(self). The first one is the proper way to call an inherited method in Python.

class RepeatingTimer(Thread):
def __init__(self, interval_seconds, callback):
super().__init__()
self.stop_event = Event()
self.interval_seconds = interval_seconds
self.callback = callback

def run(self):
while not self.stop_event.wait(self.interval_seconds):
self.callback()

def stop(self):
self.stop_event.set()

And with the functions you've defined you can do :

r1 = RepeatingTimer(1, print_r1)
r2 = RepeatingTimer(0.5, print_r2)

r1.start()
r2.start()
time.sleep(4)
r1.stop()
r2.stop()

Here is the relevant documentation for Thread.

How to repeat a function every N minutes?

use a thread

import threading

def hello_world():
threading.Timer(60.0, hello_world).start() # called every minute
print("Hello, World!")

hello_world()

Python threading.Timer only repeats once

From the documentation:

class threading.Timer

A thread that executes a function after a specified interval has passed.

This means Threading.Timer will call a function after a specified period of time. And as you noticed, it gets called only once. The solution here will to have the timer set once again at the end of the ExecuteDemo(..) function.

def ExecuteDemo():
.
.
.
threading.Timer(2, ExecuteDemo).start()

In my opinion, the above method is a little inefficient. It is like every 2 seconds a new thread is being created, and once it executes the function, it dies before creating the next thread.

I would suggest something like this:

def ExecuteDemoCaller():
#while True: # or something..
while someCondition:
ExecuteDemo()
time.sleep(2)

What is the best way to repeatedly execute a function every x seconds?

If your program doesn't have a event loop already, use the sched module, which implements a general purpose event scheduler.

import sched, time
s = sched.scheduler(time.time, time.sleep)
def do_something(sc):
print("Doing stuff...")
# do your stuff
sc.enter(60, 1, do_something, (sc,))

s.enter(60, 1, do_something, (s,))
s.run()

If you're already using an event loop library like asyncio, trio, tkinter, PyQt5, gobject, kivy, and many others - just schedule the task using your existing event loop library's methods, instead.

Run certain code every n seconds

import threading

def printit():
threading.Timer(5.0, printit).start()
print "Hello, World!"

printit()

# continue with the rest of your code

https://docs.python.org/3/library/threading.html#timer-objects

Repeating a function every few seconds

Use a timer. There are 3 basic kinds, each suited for different purposes.

  • System.Windows.Forms.Timer

Use only in a Windows Form application. This timer is processed as part of the message loop, so the the timer can be frozen under high load.

  • System.Timers.Timer

When you need synchronicity, use this one. This means that the tick event will be run on the thread that started the timer, allowing you to perform GUI operations without much hassle.

  • System.Threading.Timer

This is the most high-powered timer, which fires ticks on a background thread. This lets you perform operations in the background without freezing the GUI or the main thread.

For most cases, I recommend System.Timers.Timer.



Related Topics



Leave a reply



Submit