Categories
Python Answers

How to start a function at a given time with Python?

Spread the love

Sometimes, we want to start a function at a given time with Python.

In this article, we’ll look at how to start a function at a given time with Python.

How to start a function at a given time with Python?

To start a function at a given time with Python, we can use the timedelta function to set the delay before running the function.

For instance, we write:

from datetime import datetime, timedelta
import threading


def update():
    print('hello world')


now = datetime.now()
run_at = now + timedelta(seconds=3)
delay = (run_at - now).total_seconds()
threading.Timer(delay, update).start()

to create the update function that we want to run after a 3 second delay.

To do this, we get the current date time with datetime.now.

And then we add the 3 seconds time difference by calling the timedelta function and add the returned time delta object to now.

Next, we calculate the delay with (run_at - now).total_seconds().

Finally, we call the Timer constructor with the delay and the update function to create the thread.

And we call start on the Timer instance to run the function after the specified delay.

Therefore, we should see 'hello world' printed after a 3 seconds delay.

Conclusion

To start a function at a given time with Python, we can use the timedelta function to set the delay before running the function.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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