How to Execute a function every x seconds in python

To Execute a function every x seconds in python:

  1. Use the time.sleep() method
  2. Use the sched module
  3. Use the apscheduler module
  4. Use the threading module

Method No 1: Using time.sleep() to Execute a function every x seconds in Python

The most common way to execute a function every x seconds in Python is to use the time.sleep() method. The time.sleep() function is a Python built-in function that is used to make the program sleep for the time specified.

We can use the time.sleep to execute every x seconds. There are two differnt ways of using the time.sleep():

The wrong way to use time.sleep():

The below code doesn’t execute every 60 seconds. it puts a 60 second gap between executions. It only happens every 60 seconds if your executed code takes no time at all.

import time
while True:
    # Code executed here
    time.sleep(60)

The Good way to use the time.sleep():

import time
starttime = time.time()
while True:
    print("tick")
    time.sleep(60.0 - ((time.time() - starttime) % 60.0))

Method No 2 : Using the sched module in Python to execute Python code after interval:

We can use the sched module to call the function or a block of python code after some interval using the sched module. The sched module is a python module that is used for scheduling the code.

import sched, time
s = sched.scheduler(time.time, time.sleep)
def do_something(sc): 
    print("Doing stuff...")
    # do your stuff
    sc.enter(60, 1, do_something, (sc,))

s.enter(60, 1, do_something, (s,))
s.run()

Method No 3 : Using the apscheduler module in Python to execute the function every x seconds

You can use this third party apscheduler module in python. It is very helpful in other ways as well. You can provide other functions like blockscheduler, TwistedScheduler and many more.

from apscheduler.schedulers.background import BlockingScheduler
def print_t():
  pass

sched = BlockingScheduler()
sched.add_job(print_t, 'interval', seconds =60) #will do the print_t work for every 60 seconds

sched.start()

Method No 4 : Use threading module to execute a function after an interval

Here is a python code, that shows you how to use the threading module to execute a function after some interval. You can check it out.


import threading 
import time

class RepeatedTimer(object):
  def __init__(self, interval, function, *args, **kwargs):
    self._timer = None
    self.interval = interval
    self.function = function
    self.args = args
    self.kwargs = kwargs
    self.is_running = False
    self.next_call = time.time()
    self.start()

  def _run(self):
    self.is_running = False
    self.start()
    self.function(*self.args, **self.kwargs)

  def start(self):
    if not self.is_running:
      self.next_call += self.interval
      self._timer = threading.Timer(self.next_call - time.time(), self._run)
      self._timer.start()
      self.is_running = True

  def stop(self):
    self._timer.cancel()
    self.is_running = False

Leave a Comment

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

Scroll to Top