How To Repeatedly Execute A Function Every x Seconds?

In this tutorial, we will learn How To Repeatedly Execute A Function Every x Seconds there are different ways to do the same that we will discuss here like using time.sleep(), sched module, apscheduler module, and threading module.

Function

Calling Function

Calling function after every x seconds we use different ways to do so that we are going to discuss here.

Using time.sleep() method

It is the most common way to execute it for execution following the code given below where we need to import the time module to implement it.

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

It also uses a time module for executing the same in addition to that it also used a sched module too t]and to implement the same using this follow the code given below.

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()
Using scheduler module

This is also a very useful way to execute it along with some extra features that we do not require in this but it does the task that we want to complete for the same code is given below.

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

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

sched.start()
Thread Module

we can use the threading module to execute the same as per our choice as we will see in the example code given below.

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

 

To learn more about executing the function every x seconds visit: Executing of function every after x seconds.

Also to learn more about python visit: How To Reverse A String In Python?

To learn more about different programming languages, their tutorials, concepts, and solutions to different problems faced during learning visit: beta python programming languages Solutions

Leave a Comment

%d bloggers like this: