timakro
timakro

Reputation: 1841

Pythonmodule to make a loop run exactly every n seconds

I'm searching for a pythonmodule which provides an object which has a method that can sleep for n seconds since the last sleep. I think this example explains it:

import time

def skipped(n):
    print("Ohhh no, skipped {0} ticks!".format(n))

# the object of the module im searching for
timer = Timer()

# mainloop
while True:
    # a short calculation wouldn't cause skipped() to be called
    time.sleep(0.1)

    # but a too long calculation would
    # theoretically this should cause "Ohhh no, skipped 0.5 ticks!" to be printed
    #time.sleep(3)

    # wait until n seconds since the last sleep passed
    # if already more than n seconds passed call skipfunc((secondspassed-n)/n)
    timer.sleep(n=2, skipfunc=skipped)

But it's just an example, the object hasn't to work exactly like this. For example it would be okay too if the method would raise an exception if ticks were skipped.

Upvotes: 1

Views: 64

Answers (2)

Daniel
Daniel

Reputation: 42748

Since there are many different variants to handle this problem, and the code to do so is so easy, there is no explicit module for this:

interval = 2
while True:
    next_run = time.time() + interval
    do_something()
    delta = next_run - time.time()
    if delta < 0:
        skipped(delta/-interval)
    else:
        time.sleep(delta)

Upvotes: 3

mitghi
mitghi

Reputation: 919

threading module provides it.

import threading

def periodic_call():
    threading.Timer(0.1, periodic_call).start()
    print('from peridic_call')

periodic_call()

Upvotes: 3

Related Questions