3

I'm new to python and I'm wondering if there's a function that would repeat an event at certain intervals, kinda like

setInterval()

in Javascript. I know I could just use

time.sleep()

inside a regular loop but I'm wondering if there's a nicer way to do it. Thanks in advance.

Marwan Sabry
  • 85
  • 3
  • 9
  • 3
    You will nead threads. See [this question](http://stackoverflow.com/questions/2697039/python-equivalent-of-setinterval) (or others by searching on Google). – Delgan Nov 02 '15 at 09:01

2 Answers2

3

the following is a simplified version of @Mathias Ettinger's

Because call_at_interval runs in a separate thread already, there is no need to use Timer, since it would spawn a further thread.

Just sleep and call the callback directly.

from threading import Thread
from time import sleep

def call_at_interval(period, callback, args):
    while True:
        sleep(period)
        callback(*args)

def setInterval(period, callback, *args):
    Thread(target=call_at_interval, args=(period, callback, args)).start()

def hello(word):
    print("hello", word)

setInterval(10, hello, 'world!')
Pynchia
  • 10,996
  • 5
  • 34
  • 43
1
from threading import Timer, Thread

def call_at_interval(time, callback, args):
    while True:
        timer = Timer(time, callback, args=args)
        timer.start()
        timer.join()

def setInterval(time, callback, *args):
    Thread(target=call_at_interval, args=(time, callback, args)).start()

The two functions are needed to avoid making setInterval a blocking call.

You can use it like so:

def hello(word):
    print("hello", word)

setInterval(10, hello, 'world!')

It will print 'hello world!' every ten seconds.

301_Moved_Permanently
  • 4,007
  • 14
  • 28