How to Run Function at a Specified Time in Python

09/15/2021

Contents

In this article, you will learn how to run function at a specified time in Python.

Run function at a specified time

To run a function at a specified time in Python, you can use the built-in datetime module, which provides classes for working with dates and times. Specifically, you can use the datetime.datetime class to represent the current date and time and then use the time.sleep() function to wait until the specified time.

Here’s an example code snippet that demonstrates how to run a function at a specific time:

import datetime
import time

def my_function():
    print("Hello, world!")

# Set the time to run the function
run_time = datetime.datetime(2023, 3, 1, 10, 0, 0) # Year, Month, Day, Hour, Minute, Second

# Wait until the specified time
while datetime.datetime.now() < run_time:
    time.sleep(1)

# Call the function
my_function()

In this example, the my_function() function is defined, and the run_time variable is set to March 1st, 2023, at 10:00 AM. The while loop waits until the current time reaches run_time, using the time.sleep() function to delay execution by one second between each check. Once the current time reaches run_time, the my_function() function is called, and "Hello, world!" is printed to the console.