AnyEvent
view release on metacpan or search on metacpan
my $w = AnyEvent->child (pid => $pid, cb => sub {
my ($pid, $status) = @_;
...
});
# called when event loop idle (if applicable)
my $w = AnyEvent->idle (cb => sub { ... });
my $w = AnyEvent->condvar; # stores whether a condition was flagged
$w->send; # wake up current and all future recv's
$w->recv; # enters "main loop" till $condvar gets ->send
# use a condvar in callback mode:
$w->cb (sub { $_[0]->recv });
INTRODUCTION/TUTORIAL
This manpage is mainly a reference manual. If you are interested in a
tutorial or some gentle introduction, have a look at the AnyEvent::Intro
manpage.
SUPPORT
An FAQ document is available as AnyEvent::FAQ.
There also is a mailinglist for discussing all things AnyEvent, and an
IRC channel, too.
See the AnyEvent project page at the Schmorpforge Ta-Sa Software
Repository, at <http://anyevent.schmorp.de>, for more info.
WHY YOU SHOULD USE THIS MODULE (OR NOT)
Glib, POE, IO::Async, Event... CPAN offers event models by the dozen
nowadays. So what is different about AnyEvent?
Executive Summary: AnyEvent is *compatible*, AnyEvent is *free of
policy* and AnyEvent is *small and efficient*.
First and foremost, *AnyEvent is not an event model* itself, it only
interfaces to whatever event model the main program happens to use, in a
pragmatic way. For event models and certain classes of immortals alike,
the statement "there can only be one" is a bitter reality: In general,
only one event loop can be active at the same time in a process.
AnyEvent cannot change this, but it can hide the differences between
those event loops.
The goal of AnyEvent is to offer module authors the ability to do event
programming (waiting for I/O or timer events) without subscribing to a
religion, a way of living, and most importantly: without forcing your
module users into the same thing by forcing them to use the same event
model you use.
For modules like POE or IO::Async (which is a total misnomer as it is
actually doing all I/O *synchronously*...), using them in your module is
like joining a cult: After you join, you are dependent on them and you
cannot use anything else, as they are simply incompatible to everything
that isn't them. What's worse, all the potential users of your module
are *also* forced to use the same event loop you use.
AnyEvent is different: AnyEvent + POE works fine. AnyEvent + Glib works
fine. AnyEvent + Tk works fine etc. etc. but none of these work together
with the rest: POE + EV? No go. Tk + Event? No go. Again: if your module
uses one of those, every user of your module has to use it, too. But if
your module uses AnyEvent, it works transparently with all event models
it supports (including stuff like IO::Async, as long as those use one of
the supported event loops. It is easy to add new event loops to
AnyEvent, too, so it is future-proof).
In addition to being free of having to use *the one and only true event
model*, AnyEvent also is free of bloat and policy: with POE or similar
modules, you get an enormous amount of code and strict rules you have to
follow. AnyEvent, on the other hand, is lean and to the point, by only
offering the functionality that is necessary, in as thin as a wrapper as
technically possible.
Of course, AnyEvent comes with a big (and fully optional!) toolbox of
useful functionality, such as an asynchronous DNS resolver, 100%
non-blocking connects (even with TLS/SSL, IPv6 and on broken platforms
such as Windows) and lots of real-world knowledge and workarounds for
platform bugs and differences.
Now, if you *do want* lots of policy (this can arguably be somewhat
useful) and you want to force your users to use the one and only event
model, you should *not* use this module.
DESCRIPTION
AnyEvent provides a uniform interface to various event loops. This
allows module authors to use event loop functionality without forcing
module users to use a specific event loop implementation (since more
than one event loop cannot coexist peacefully).
The interface itself is vaguely similar, but not identical to the Event
module.
During the first call of any watcher-creation method, the module tries
to detect the currently loaded event loop by probing whether one of the
following modules is already loaded: EV, AnyEvent::Loop, Event, Glib,
Tk, Event::Lib, Qt, POE. The first one found is used. If none are
detected, the module tries to load the first four modules in the order
given; but note that if EV is not available, the pure-perl
AnyEvent::Loop should always work, so the other two are not normally
tried.
Because AnyEvent first checks for modules that are already loaded,
loading an event model explicitly before first using AnyEvent will
likely make that model the default. For example:
use Tk;
use AnyEvent;
# .. AnyEvent will likely default to Tk
The *likely* means that, if any module loads another event model and
starts using it, all bets are off - this case should be very rare
though, as very few modules hardcode event loops without announcing this
very loudly.
The pure-perl implementation of AnyEvent is called "AnyEvent::Loop".
Like other event modules you can load it explicitly and enjoy the high
availability of that event loop :)
WATCHERS
AnyEvent has the central concept of a *watcher*, which is an object that
stores relevant data for each kind of event you are waiting for, such as
In list context, all parameters passed to "send" will be returned,
in scalar context only the first one will be returned.
Note that doing a blocking wait in a callback is not supported by
any event loop, that is, recursive invocation of a blocking "->recv"
is not allowed and the "recv" call will "croak" if such a condition
is detected. This requirement can be dropped by relying on
Coro::AnyEvent , which allows you to do a blocking "->recv" from any
thread that doesn't run the event loop itself. Coro::AnyEvent is
loaded automatically when Coro is used with AnyEvent, so code does
not need to do anything special to take advantage of that: any code
that would normally block your program because it calls "recv", be
executed in an "async" thread instead without blocking other
threads.
Not all event models support a blocking wait - some die in that case
(programs might want to do that to stay interactive), so *if you are
using this from a module, never require a blocking wait*. Instead,
let the caller decide whether the call will block or not (for
example, by coupling condition variables with some kind of request
results and supporting callbacks so the caller knows that getting
the result will not block, while still supporting blocking waits if
the caller so desires).
You can ensure that "->recv" never blocks by setting a callback and
only calling "->recv" from within that callback (or at a later
time). This will work even when the event loop does not support
blocking waits otherwise.
$bool = $cv->ready
Returns true when the condition is "true", i.e. whether "send" or
"croak" have been called.
$cb = $cv->cb ($cb->($cv))
This is a mutator function that returns the callback set (or "undef"
if not) and optionally replaces it before doing so.
The callback will be called when the condition becomes "true", i.e.
when "send" or "croak" are called, with the only argument being the
condition variable itself. If the condition is already true, the
callback is called immediately when it is set. Calling "recv" inside
the callback or at any later time is guaranteed not to block.
Additionally, when the callback is invoked, it is also removed from
the condvar (reset to "undef"), so the condvar does not keep a
reference to the callback after invocation.
SUPPORTED EVENT LOOPS/BACKENDS
The following backend classes are part of the AnyEvent distribution
(every class has its own manpage):
Backends that are autoprobed when no other event loop can be found.
EV is the preferred backend when no other event loop seems to be in
use. If EV is not installed, then AnyEvent will fall back to its own
pure-perl implementation, which is available everywhere as it comes
with AnyEvent itself.
AnyEvent::Impl::EV based on EV (interface to libev, best choice).
AnyEvent::Impl::Perl pure-perl AnyEvent::Loop, fast and portable.
Backends that are transparently being picked up when they are used.
These will be used if they are already loaded when the first watcher
is created, in which case it is assumed that the application is
using them. This means that AnyEvent will automatically pick the
right backend when the main program loads an event module before
anything starts to create watchers. Nothing special needs to be done
by the main program.
AnyEvent::Impl::Event based on Event, very stable, few glitches.
AnyEvent::Impl::Glib based on Glib, slow but very stable.
AnyEvent::Impl::Tk based on Tk, very broken.
AnyEvent::Impl::UV based on UV, innovated square wheels.
AnyEvent::Impl::EventLib based on Event::Lib, leaks memory and worse.
AnyEvent::Impl::POE based on POE, very slow, some limitations.
AnyEvent::Impl::Irssi used when running within irssi.
AnyEvent::Impl::IOAsync based on IO::Async.
AnyEvent::Impl::Cocoa based on Cocoa::EventLoop.
AnyEvent::Impl::FLTK based on FLTK (fltk 2 binding).
Backends with special needs.
Qt requires the Qt::Application to be instantiated first, but will
otherwise be picked up automatically. As long as the main program
instantiates the application before any AnyEvent watchers are
created, everything should just work.
AnyEvent::Impl::Qt based on Qt.
Event loops that are indirectly supported via other backends.
Some event loops can be supported via other modules:
There is no direct support for WxWidgets (Wx) or Prima.
WxWidgets has no support for watching file handles. However, you can
use WxWidgets through the POE adaptor, as POE has a Wx backend that
simply polls 20 times per second, which was considered to be too
horrible to even consider for AnyEvent.
Prima is not supported as nobody seems to be using it, but it has a
POE backend, so it can be supported through POE.
AnyEvent knows about both Prima and Wx, however, and will try to
load POE when detecting them, in the hope that POE will pick them
up, in which case everything will be automatic.
Known event loops outside the AnyEvent distribution
The following event loops or programs support AnyEvent by providing
their own AnyEvent backend. They will be picked up automatically.
urxvt::anyevent available to rxvt-unicode extensions
GLOBAL VARIABLES AND FUNCTIONS
These are not normally required to use AnyEvent, but can be useful to
write AnyEvent extension modules.
$AnyEvent::MODEL
Contains "undef" until the first watcher is being created, before
the backend has been autodetected.
Afterwards it contains the event model that is being used, which is
the name of the Perl class implementing the model. This class is
usually one of the "AnyEvent::Impl::xxx" modules, but can be any
There will always be a single main program - the only place that should
dictate which event model to use.
If the program is not event-based, it need not do anything special, even
when it depends on a module that uses an AnyEvent. If the program itself
uses AnyEvent, but does not care which event loop is used, all it needs
to do is "use AnyEvent". In either case, AnyEvent will choose the best
available loop implementation.
If the main program relies on a specific event model - for example, in
Gtk2 programs you have to rely on the Glib module - you should load the
event module before loading AnyEvent or any module that uses it:
generally speaking, you should load it as early as possible. The reason
is that modules might create watchers when they are loaded, and AnyEvent
will decide on the event model to use as soon as it creates watchers,
and it might choose the wrong one unless you load the correct one
yourself.
You can chose to use a pure-perl implementation by loading the
"AnyEvent::Loop" module, which gives you similar behaviour everywhere,
but letting AnyEvent chose the model is generally better.
MAINLOOP EMULATION
Sometimes (often for short test scripts, or even standalone programs who
only want to use AnyEvent), you do not want to run a specific event
loop.
In that case, you can use a condition variable like this:
AnyEvent->condvar->recv;
This has the effect of entering the event loop and looping forever.
Note that usually your program has some exit condition, in which case it
is better to use the "traditional" approach of storing a condition
variable somewhere, waiting for it, and sending it when the program
should exit cleanly.
OTHER MODULES
The following is a non-exhaustive list of additional modules that use
AnyEvent as a client and can therefore be mixed easily with other
AnyEvent modules and other event loops in the same program. Some of the
modules come as part of AnyEvent, the others are available via CPAN (see
<http://search.cpan.org/search?m=module&q=anyevent%3A%3A*> for a longer
non-exhaustive list), and the list is heavily biased towards modules of
the AnyEvent author himself :)
AnyEvent::Util (part of the AnyEvent distribution)
Contains various utility functions that replace often-used blocking
functions such as "inet_aton" with event/callback-based versions.
AnyEvent::Socket (part of the AnyEvent distribution)
Provides various utility functions for (internet protocol) sockets,
addresses and name resolution. Also functions to create non-blocking
tcp connections or tcp servers, with IPv6 and SRV record support and
more.
AnyEvent::Handle (part of the AnyEvent distribution)
Provide read and write buffers, manages watchers for reads and
writes, supports raw and formatted I/O, I/O queued and fully
transparent and non-blocking SSL/TLS (via AnyEvent::TLS).
AnyEvent::DNS (part of the AnyEvent distribution)
Provides rich asynchronous DNS resolver capabilities.
AnyEvent::HTTP, AnyEvent::IRC, AnyEvent::XMPP, AnyEvent::GPSD,
AnyEvent::IGS, AnyEvent::FCP
Implement event-based interfaces to the protocols of the same name
(for the curious, IGS is the International Go Server and FCP is the
Freenet Client Protocol).
AnyEvent::AIO (part of the AnyEvent distribution)
Truly asynchronous (as opposed to non-blocking) I/O, should be in
the toolbox of every event programmer. AnyEvent::AIO transparently
fuses IO::AIO and AnyEvent together, giving AnyEvent access to
event-based file I/O, and much more.
AnyEvent::Fork, AnyEvent::Fork::RPC, AnyEvent::Fork::Pool,
AnyEvent::Fork::Remote
These let you safely fork new subprocesses, either locally or
remotely (e.g.v ia ssh), using some RPC protocol or not, without the
limitations normally imposed by fork (AnyEvent works fine for
example). Dynamically-resized worker pools are obviously included as
well.
And they are quite tiny and fast as well - "abusing" AnyEvent::Fork
just to exec external programs can easily beat using "fork" and
"exec" (or even "system") in most programs.
AnyEvent::Filesys::Notify
AnyEvent is good for non-blocking stuff, but it can't detect file or
path changes (e.g. "watch this directory for new files", "watch this
file for changes"). The AnyEvent::Filesys::Notify module promises to
do just that in a portbale fashion, supporting inotify on GNU/Linux
and some weird, without doubt broken, stuff on OS X to monitor
files. It can fall back to blocking scans at regular intervals
transparently on other platforms, so it's about as portable as it
gets.
(I haven't used it myself, but it seems the biggest problem with it
is it quite bad performance).
AnyEvent::DBI
Executes DBI requests asynchronously in a proxy process for you,
notifying you in an event-based way when the operation is finished.
AnyEvent::FastPing
The fastest ping in the west.
Coro
Has special support for AnyEvent via Coro::AnyEvent, which allows
you to simply invert the flow control - don't call us, we will call
you:
async {
Coro::AnyEvent::sleep 5; # creates a 5s timer and waits for it
print "5 seconds later!\n";
Coro::AnyEvent::readable *STDIN; # uses an I/O watcher
my $line = <STDIN>; # works for ttys
AnyEvent::HTTP::http_get "url", Coro::rouse_cb;
my ($body, $hdr) = Coro::rouse_wait;
};
SIMPLIFIED AE API
Starting with version 5.0, AnyEvent officially supports a second, much
simpler, API that is designed to reduce the calling, typing and memory
overhead by using function call syntax and a fixed number of parameters.
See the AE manpage for details.
ERROR AND EXCEPTION HANDLING
In general, AnyEvent does not do any error handling - it relies on the
caller to do that if required. The AnyEvent::Strict module (see also the
"PERL_ANYEVENT_STRICT" environment variable, below) provides strict
checking of all AnyEvent methods, however, which is highly useful during
development.
As for exception handling (i.e. runtime errors and exceptions thrown
while executing a callback), this is not only highly event-loop
specific, but also not in any way wrapped by this module, as this is the
job of the main program.
The pure perl event loop simply re-throws the exception (usually within
"condvar->recv"), the Event and EV modules call "$Event/EV::DIED->()",
Glib uses "install_exception_handler" and so on.
ENVIRONMENT VARIABLES
AnyEvent supports a number of environment variables that tune the
runtime behaviour. They are usually evaluated when AnyEvent is loaded,
initialised, or a submodule that uses them is loaded. Many of them also
cause AnyEvent to load additional modules - for example,
"PERL_ANYEVENT_DEBUG_WRAP" causes the AnyEvent::Debug module to be
loaded.
All the environment variables documented here start with
( run in 0.605 second using v1.01-cache-2.11-cpan-39bf76dae61 )