Skip to content Skip to sidebar Skip to footer

Equivalent Of Setinterval In Python

I have recently posted a question about how to postpone execution of a function in Python (kind of equivalent to Javascript setTimeout) and it turns out to be a simple task using t

Solution 1:

Your solution looks fine to me.

There are several ways to communicate with threads. To order a thread to stop, you can use threading.Event(), which has a wait() method that you can use instead of time.sleep().

stop_event = threading.Event()
...
stop_event.wait(1.)
if stop_event.isSet():
    return
...

For your thread to exit when the program is terminated, set its daemon attribute to True before calling start(). This applies to Timer() objects as well because they subclass threading.Thread. See http://docs.python.org/library/threading.html#threading.Thread.daemon

Solution 2:

Maybe these are the easiest setInterval equivalent in python:

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

Solution 3:

Maybe a bit simpler is to use recursive calls to Timer:

from threading import Timer
import atexit

classRepeat(object):

    count = 0    @staticmethoddefrepeat(rep, delay, func):
        "repeat func rep times with a delay given in seconds"if Repeat.count < rep:
            # call func, you might want to add args here
            func()
            Repeat.count += 1# setup a timer which calls repeat recursively# again, if you need args for func, you have to add them here
            timer = Timer(delay, Repeat.repeat, (rep, delay, func))
            # register timer.cancel to stop the timer when you exit the interpreter
            atexit.register(timer.cancel)
            timer.start()

deffoo():
    print"bar"

Repeat.repeat(3,2,foo)

atexit allows to signal stopping with CTRL-C.

Solution 4:

this class Interval

classali:def__init__(self):
        self.sure = True;

    defaliv(self,func,san):
        print "ali naber";
        self.setInterVal(func, san);

    defsetInterVal(self,func, san):

        # istenilen saniye veya dakika aralığında program calışır. deffunc_Calistir():

            func(func,san);  #calışıcak fonksiyon.self.t = threading.Timer(san, func_Calistir)
        self.t.start()
        returnself.t


a = ali();
a.setInterVal(a.aliv,5);

Post a Comment for "Equivalent Of Setinterval In Python"