How to call a function every N seconds in Python?

Automation of python functions is very useful, like creating a backup every n seconds. In this python article, we will learn How to repeatedly execute a function every N seconds in Python.

Table Of Contents

Method 1: Using time module

First method we can use to repeatedly execute a function every N seconds in Python is the sleep() function of time module. The time module comes pre-installed with python programming language and provides the functions for working with time, including retrieving the current time, converting between different time formats, and sleeping (pausing) the execution of a program.

time.sleep() :

This function allows you to pause the execution of your program for a specified number of seconds. This takes only one argument which is the number of seconds.

See an Example code below:

CODE :

# importing time module.
import time

# main function which will be initialized after n seconds.
def main() :
    # time.asctime() prints the current date & time in string.
    print('Program Executed @',time.asctime())

# initialized a counter.
n = 1

# runs until n < 5,just to avoid the infinite loop.
# this will execute the main() func in every 5 seconds.
while n < 5:
    main()
    time.sleep(5)
    n = n+1

OUTPUT :

Program Executed @ Wed Jan 4 01:27:37 2023
Program Executed @ Wed Jan 4 01:27:42 2023
Program Executed @ Wed Jan 4 01:27:47 2023
Program Executed @ Wed Jan 4 01:27:52 2023
....
....

So, In the above example, by using the sleep() function from time module, we executed a function after every N seconds. Here the main() function runs at every 5 seconds. Also a counter has been used with the variable n, which ensures that this does not go into an infinite loop.

Method 2: Using sched module

Another module we can use to repeatedly execute a function every N seconds in Python is sched module which comes pre-installed with Python programming language. It allows you to schedule a function to be called at a specific time, or to be called repeatedly at a specified interval.

See an Example code below:

CODE :

# importing time and sched module
import sched, time

# main function which will be initialized after n seconds.
def main(sc) :
    # time.asctime() prints the current date & time in string.
    print('Program Executed @',time.asctime())

# Create a scheduler instance
sc = sched.scheduler()

# initialized a counter.
n = 1

# runs until n < 5,just to avoid the infinite loop.
# this will execute the main() func in every 5 seconds.
while n < 5:
    # Schedule the event to be executed in 5 seconds
    sc.enter(5, 1, main, (sc,))
    # Run the scheduler
    sc.run()
    n = n+1

OUTPUT :

Program Executed @ Wed Jan 4 12:24:04 2023
Program Executed @ Wed Jan 4 12:24:10 2023
Program Executed @ Wed Jan 4 12:24:15 2023
Program Executed @ Wed Jan 4 12:24:20 2023

In the above code, the sched module has been used to repeatedly execute a function every N seconds in Python. Here sc has been used as an argument in sc.enter() while scheduling the event. The sc is an instance of the scheduler class. The scheduler class is used to schedule the execution of events at certain times. The enter() method is used to schedule an event to be executed after a certain number of seconds.

Method 3: Using threading module

Threading module comes pre-installed with Python programming language, which can be used to repeatedly execute a function every N seconds in Python. Threading module in Python provides a simple interface for working with threads. Threads are used to run multiple pieces of code concurrently within a single program. Here we will be using threading module to create a new thread that executes the function, and then use the threading.Timer class to execute the function every N seconds.

See an Example code below:

CODE :

# Importing threading and time module.
import threading,time

def main():
    # time.asctime() prints the current date & time in string.
    print('Program Executed @',time.asctime())

def run():
    # created a global variable.
    global counter
    counter += 1

    # stop after 5 executions
    if counter < 5:
        # where 5 is the number of seconds to wait
        threading.Timer(5, run).start()
    # running the main function
    main()

counter = 0
run()

OUTPUT :

Program Executed @ Wed Jan 4 13:33:53 2023
Program Executed @ Wed Jan 4 13:33:58 2023
Program Executed @ Wed Jan 4 13:34:03 2023
Program Executed @ Wed Jan 4 13:34:08 2023
Program Executed @ Wed Jan 4 13:34:13 2023

Summary

In this Python article, we learned about modules like: time, sched and threading. Also we used methods from three different modules to execute a function every N seconds in Python. You can always use any of the methods/module you want but the most easy to understand and use is sleep() function of time module which just takes one argument which is N seconds after which you want to execute a certain block of code. Thanks.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top