Skip to content Skip to sidebar Skip to footer

A Way To Almost Correctly Trigger A Function Periodically

I would like to trigger a function periodically, lets say, each 5s. The function will not consume many CPU time, so I expect that even if it is a blocking function it will not be a

Solution 1:

The second approach described in the question makes a busy loop (eating all CPU).

Another simpler approach than using threads is to use the good old select system call:

import time
import select
import socket# win

s = socket.socket() # win# Function to trigger:
def q(t0, t1):
    print("{}: {}".format(t1, t1-t0))

# Scheduler:
t0 = time.time()
while True:
    select.select([s],[],[],5) #wait for 5 seconds (dummy socket for win)
    t1 = time.time()
    q(t0, t1)
    t0 = t1

Results:

1441792007.3: 5.005249977111441792012.3: 5.005549907681441792017.31: 5.005208969121441792022.31: 5.005089044571441792027.32: 5.005180120471441792032.32: 5.005239963531441792037.33: 5.00523781776

Also, time.clock doesn't work for me on Linux. Documentation says:

The method clock() returns the current processor time as a floating point number expressed in seconds on Unix. The precision depends on that of the C function of the same name, but in any case, this is the function to use for benchmarking Python or timing algorithms.

On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter.

Maybe you're on Windows ? Or you're on Linux but as the second example is making CPU busy, time.clock really gives a number whereas with my code it is always 0 since no CPU cycles are really involved.

Post a Comment for "A Way To Almost Correctly Trigger A Function Periodically"