[Python-Dev] Non-blocking (asynchronous) timer without thread?

Josiah Carlson jcarlson at uci.edu
Sat Dec 23 07:01:40 CET 2006


Evgeniy Khramtsov <xramtsov at gmail.com> wrote:
> 
> The question to python core developers:
> Is there any plans to implement non-blocking timer like a 
> threading.Timer() but without thread?
> Some interpreted languages (like Tcl or Erlang) have such functionality, 
> so I think it would be a great
> feature in Python :)
> 
> The main goal is to prevent threads overhead and problems with race 
> conditions and deadlocks.

How would you propose a non-threaded timer work?  Would it involve the
writing of a scheduler and the execution of scheduled tasks in a
scheduler?  If so, you can implement it today (I would suggest using the
heapq module, and/or the pair heap I posted to this list a few weeks ago),
or you can use a previously existing mainloop for handling events
(wx.App().MainLoop() works well, you just need to write a wx.EvtHandler
subclass).  Heck, you could even use Twisted's event loop to handle it.

If you were really crazy, you could even use exceptions to signal that
an event was ready...

    import time
    import sys
    _scheduled = []

    def hook(*args):
        if _scheduled and time.time() >= _scheduled[0][0]:
            raise Exception("Scheduled Event Pending!")

    sys.settrace(hook)

Aside from using a library that does it for you, or hooking into native
message hooks (I'm sure that Windows has a "notify this process in X
seconds" message), I personally don't see a way of making what you want
happen work in Python, or even *how* you would signal to the only thread
in your application, "hey, there is this other task that should happen"
that is substantially different from a periodic "if time.time() >=
scheduled" check.


 - Josiah



More information about the Python-Dev mailing list