[Tutor] timed functions? Timeouts?

Kent Johnson kent37 at tds.net
Tue May 20 03:23:58 CEST 2008


On Mon, May 19, 2008 at 5:28 PM, W W <srilyk at gmail.com> wrote:
> Now, when I look at that example and try to translate the timeout to
> what I think is going on "behind the scenes" I'm pretty sure it spawns
> a thread that does something similar to this:
>
>   1 import time
>  2
>  3 def timer(end, exe):
>  4     start = time.time()
>  5     while True:
>  6       now = time.time()
>  7       if (now - start) >= end:
>  8         break
>  9     exe()
>  10
>  11 def execute_this():
>  12    for x in range(1, 10):
>  13      print x
>  14
>  15 timer(5, execute_this)
>
> Am I correct? Is there a python built-in for this? Where should I go
> to learn more? Is there anything "wrong" with using a function like
> this?

You are pretty much on the right track but you should put a
time.sleep() in your loop or it will chew up all available CPU time.
Even better, figure out how long you need to sleep.

The sched module in the standard library might help though it doesn't
seem to do any threading. Also look at these recipes:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496800
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/114644

Kent


More information about the Tutor mailing list