Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Equivalent of setInterval()?

Does Python have a function similar to JavaScript's setInterval()?

I would like to have:

def set_interval(func, interval):     ... 

That will call func every interval time units.

like image 658
zjm1126 Avatar asked Apr 23 '10 08:04

zjm1126


People also ask

What can I use instead of setInterval?

Nested setTimeout calls are a more flexible alternative to setInterval , allowing us to set the time between executions more precisely. Zero delay scheduling with setTimeout(func, 0) (the same as setTimeout(func) ) is used to schedule the call “as soon as possible, but after the current script is complete”.

What is the correct syntax to call the setInterval () function?

The setInterval() method is JavaScript is used to evaluate an expression at intervals. Here's the syntax: setInterval(function, interval_in_milliseconds, param1, param2, param3...) Here, interval_in_milliseconds sets the intervals in milliseconds, after the code will execute.

Is setInterval a callback function?

Introduction to JavaScript setInterval() The setInterval() repeatedly calls a function with a fixed delay between each call. In this syntax: The callback is a callback function to be executed every delay milliseconds.


2 Answers

This might be the correct snippet you were looking for:

import threading  def set_interval(func, sec):     def func_wrapper():         set_interval(func, sec)         func()     t = threading.Timer(sec, func_wrapper)     t.start()     return t 
like image 136
stamat Avatar answered Sep 22 '22 01:09

stamat


This is a version where you could start and stop. It is not blocking. There is also no glitch as execution time error is not added (important for long time execution with very short interval as audio for example)

import time, threading  StartTime=time.time()  def action() :     print('action ! -> time : {:.1f}s'.format(time.time()-StartTime))   class setInterval :     def __init__(self,interval,action) :         self.interval=interval         self.action=action         self.stopEvent=threading.Event()         thread=threading.Thread(target=self.__setInterval)         thread.start()      def __setInterval(self) :         nextTime=time.time()+self.interval         while not self.stopEvent.wait(nextTime-time.time()) :             nextTime+=self.interval             self.action()      def cancel(self) :         self.stopEvent.set()  # start action every 0.6s inter=setInterval(0.6,action) print('just after setInterval -> time : {:.1f}s'.format(time.time()-StartTime))  # will stop interval in 5s t=threading.Timer(5,inter.cancel) t.start() 

Output is :

just after setInterval -> time : 0.0s action ! -> time : 0.6s action ! -> time : 1.2s action ! -> time : 1.8s action ! -> time : 2.4s action ! -> time : 3.0s action ! -> time : 3.6s action ! -> time : 4.2s action ! -> time : 4.8s 
like image 44
doom Avatar answered Sep 23 '22 01:09

doom