Categories
Python Answers

How to run certain code every n seconds with Python?

Spread the love

Sometimes, we want to run certain code every n seconds with Python.

In this article, we’ll look at how to run certain code every n seconds with Python.

How to run certain code every n seconds with Python?

To run certain code every n seconds with Python, we can use the threading.Timer class.

For instance, we write

import threading

def printit():
  threading.Timer(5.0, printit).start()
  print("Hello, World")

printit()

to run the printit function after 5 seconds.

With threading.Timer(5.0, printit).start().

We use printit as the function to run when creating the Timer so it’ll run every 5 seconds.

Conclusion

To run certain code every n seconds with Python, we can use the threading.Timer class.

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 *