[Twisted-Python] how to get an idle callback while running a reactor?

Christopher Armstrong radix at twistedmatrix.com
Sat Dec 20 11:35:56 EST 2008

On Sat, Dec 20, 2008 at 10:28 AM, Joe Strout <joe at strout.net> wrote:
> Jean-Paul Calderone wrote:
>>> So I'm at a loss as to how to add an "idle" function that will allow my
>>> bot to periodically see whether it has something new to say to the user.
>> While this sometimes makes sense, it's usually *not* the approach you want
>> to take.  You're describing a solution which is essentially polling.  And
>> polling is not as good as responding to events.  You *could* run a
>> function
>> ten times a second that looks around for a message to send and sends it if
>> it finds one.  Or, whatever event occurs which creates those messages
>> could
>> just send the message instead of putting it in a pile and waiting for your
>> poller to find it.
> Well, the thing is that there will actually be a great many things that
> could cause it to need to send a message, such as the time, a change in the
> outside temperature, a certain change in the value of a stock fund, etc.
>  And the AIM interface isn't the only interface to this bot.  So I really do
> think I need a way to call a function once every few seconds.

Just because you have a number of sources doesn't mean you
intrinsically can't use them in an efficient, event-oriented manner.
And you don't need a time-based call *just* because you have more than
one interface to the bot.

A timed poll may end up the easiest solution for you, but I want to
make sure you understand the way events work, because there may be a
much better solution. Let's go over your example event sources:

Time - Easy: your event source there is reactor.callLater itself.
Change in the temperature - How does your thermostat communicate this
information? A serial connection? a TCP socket? in any case, you can
probably hook up to that event source with Twisted directly.
Stock price - same question.

The point is that you can hook into these event sources with some code
that will immediately send the message out over your AIM (or IRC, or
whatever other) interface to the bot. That means communication will be
instantaneous *and* efficient.

Christopher Armstrong

More information about the Twisted-Python mailing list