Python: Threading Callback Timer

March 27th, 2008 mysurface Posted in Developer, python | Hits: 89459 | 6 Comments »

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:


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, you can download and execute it like this:


6 Responses to “Python: Threading Callback Timer”

  1. This is a great example! In PHP you can use the sleep() command. You have to watch out for MAX_EXECUTION_TIME in PHP tho. This is not threaded or a call back timer but here is some PHP code to do the same thing:

    php -r '$var = array(); $var[] = "Linux"; $var[] = "Blog"; for ($x = 0; $x = 1; $x++) { sleep(1); echo $var[rand(0,1)]."\t ".date("G\:i\:s")."\n"; }'
  2. Sikisfieseaby Says:

    propecia at most unbeyond considerationably-castigation

  3. Can you provide more information on this? i have read other websites that are on similar subjects.

  4. Very nice information. Thanks for this.its great to see someone with a like mind.

  5. I believe that is one of the so much important info for me. And i am happy reading your article. But want to remark on few general issues, The website style is ideal, the articles is actually great : D. Good process, cheers

  6. Generally I don’t read post on blogs, however I wish to say that this write-up very
    pressured me to try and do it! Your writing taste has been surprised me.
    Thank you, quite nice post.

Leave a Reply