Ask Your Question
3

What is the way to execute my Python function within a thread every 5 minutes?

asked 2021-04-30 11:00:00 +0000

devzero gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-08-02 02:00:00 +0000

pufferfish gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-04-30 11:00:00 +0000

Seen: 9 times

Last updated: Aug 02 '21