Creating an event loop

Peter Hansen peter at engcorp.com
Sun Apr 9 17:21:54 EDT 2006


Fabian Steiner wrote:
> I am currently wondering how to write something like an "event loop".
> For example, if I want to write a function that checks whether a file
> was added or removed in a directory I would think of a "while 1: ..."
> construct that checks the mtime of the directory. Is this the right way
> to achieve the exepected result or are there any better ways?

That's fine for a start, provided you always insert a small time.sleep() 
call so that you don't use up all the CPU time wastefully checking for 
something that happens very rarely.  In the end, it's a tradeoff between 
CPU usage and "latency", because if you use (for example) time.sleep(5), 
you won't waste much time but you will also take up to 5 seconds to 
notice that the directory has changed.

Usually values like 0.1 (100ms) work well for things that need a quick 
response, while 2s works nicely for things that don't.  Even Python is 
pretty unnoticeable if it wakes up only every two seconds for a brief 
bit of processing.

-Peter




More information about the Python-list mailing list