You can use the threading
and time
modules in Python to execute a function every 5 minutes within a thread:
import threading
import time
def my_function():
# code to be executed every 5 minutes
print("Function executed")
def repeat_function(interval):
while True:
my_function()
time.sleep(interval)
t = threading.Thread(target=repeat_function, args=(300,), daemon=True)
t.start() # start the thread
In this example, my_function
is the function that you want to execute every 5 minutes. The repeat_function
function is the one that sets up the thread and repeats the execution of my_function
. The interval
parameter sets the time interval between each execution of my_function
, which is set to 300 seconds (5 minutes) in this example.
The t = threading.Thread(target=repeat_function, args=(300,), daemon=True)
line creates a new thread with repeat_function
as the target function and passes the interval
argument. The daemon=True
parameter makes the thread a daemon thread, which means the thread will terminate when the main thread exits.
The t.start()
line starts the thread and the execution of my_function
will start every 5 minutes.
Asked: 2021-04-30 11:00:00 +0000
Seen: 9 times
Last updated: Aug 02 '21