In this tutorial, we will learn about how to run a function after a specific time in python. you can use the time.sleep function from the time module. This will pause the execution of your program for a specified number of seconds before running the function. A Function is a set of statements, written to perform specific operations.
using time.sleep()
This method is straight forward but blocks the execution of the program during the sleep period.
using threading. Timer
This method allows the function to be scheduled without blocking the main thread.
using sched module
For more complex scheduling, the sched module can be used.
Here’s a basic example:
1.Import the necessary module:
import time
2. Define your function:
def great(): print("Hello, world!")
3. Use time.sleep to wait before running the function:
def run_after_delay(func, delay): time.sleep(dealy) func() # Example usage run_after_delay(greet, 5) # This will run the 'greet' function after a 5-second delay
Here’s the complete example:
import time def greet(): print("Hello, world!") def run_after_delay(func, delay): time.sleep(delay) func() # Run the 'greet' function after a 5-second delay run_after_delay(greet, 5)
Example Use Case:
If you want to run any other function with a delay, you can simply pass the function name and the delay time in seconds to run_after_delay. For instance:
def say_goodbye(): print("Goodbye, world!") run_after_delay(say_goodbye, 10) # This will run the 'say_goodbye' function after 1 10-second delay
Using this approach, you can delay the execution of any function in your Python code