Quantcast
Channel: Linux by Examples » python
Viewing all articles
Browse latest Browse all 10

Python: Threading Callback Timer

$
0
0

It is very common that we need to run certain routines periodically, thats why in *nix environment we have cron and in windows OS we have task scheduler. But there comes a time, we may need to execute certain routines finite times within our scripts. Under certain circumtances routines may need to run at background, probably the interval is as short as 0.1 seconds. That is the time we need a threading callback timer.

I have wrote a threading callback timer class for python, you can get it from HERE.

class ttimer takes in few parameters, they are:
interval – interval callback periodically, in sec
retry – execute how many times? -1 is infinity
cbfunc – callback function
cbparam – parameter in list

Let say I define a function to callback,

def dummy_cbf(param=[]):
    print "hello world"

In order to call dummy_cbf() for 10 times with interval 1 sec, here is what I do:

tm=ttimer(1,10,dummy_cbf)
tm.Start()

ttimer will run dummy_cbf() in a thread. The thread will died if you script end, therefore you will need to stop the thread manually before your app exit. If in the middle of something, you want to stop the timer, you can call Stop(). And if you want to check whether the timer is stop, you can call IsStop().

I do includes the sample main function in ttimer.py, you can download and execute it like this:

python ttimer.py

Viewing all articles
Browse latest Browse all 10

Trending Articles