AnyEvent
view release on metacpan or search on metacpan
lib/AnyEvent.pm view on Meta::CPAN
idea about the "current time" (being potentially far in the past, when the
script ran the last time). In that case you should arrange a call to C<<
AnyEvent->now_update >> each time the web server process wakes up again
(e.g. at the start of your script, or in a handler).
Note that updating the time I<might> cause some events to be handled.
=back
=head2 SIGNAL WATCHERS
$w = AnyEvent->signal (signal => <uppercase_signal_name>, cb => <callback>);
You can watch for signals using a signal watcher, C<signal> is the signal
I<name> in uppercase and without any C<SIG> prefix, C<cb> is the Perl
callback to be invoked whenever a signal occurs.
Although the callback might get passed parameters, their value and
presence is undefined and you cannot rely on them. Portable AnyEvent
callbacks cannot use arguments passed to signal watcher callbacks.
Multiple signal occurrences can be clumped together into one callback
invocation, and callback invocation will be synchronous. Synchronous means
that it might take a while until the signal gets handled by the process,
but it is guaranteed not to interrupt any other callbacks.
The main advantage of using these watchers is that you can share a signal
between multiple watchers, and AnyEvent will ensure that signals will not
interrupt your program at bad times.
This watcher might use C<%SIG> (depending on the event loop used),
so programs overwriting those signals directly will likely not work
correctly.
Example: exit on SIGINT
my $w = AnyEvent->signal (signal => "INT", cb => sub { exit 1 });
=head3 Restart Behaviour
While restart behaviour is up to the event loop implementation, most will
not restart syscalls (that includes L<Async::Interrupt> and AnyEvent's
pure perl implementation).
=head3 Safe/Unsafe Signals
Perl signals can be either "safe" (synchronous to opcode handling)
or "unsafe" (asynchronous) - the former might delay signal delivery
indefinitely, the latter might corrupt your memory.
AnyEvent signal handlers are, in addition, synchronous to the event loop,
i.e. they will not interrupt your running perl program but will only be
called as part of the normal event handling (just like timer, I/O etc.
callbacks, too).
=head3 Signal Races, Delays and Workarounds
Many event loops (e.g. Glib, Tk, Qt, IO::Async) do not support
attaching callbacks to signals in a generic way, which is a pity,
as you cannot do race-free signal handling in perl, requiring
C libraries for this. AnyEvent will try to do its best, which
means in some cases, signals will be delayed. The maximum time
a signal might be delayed is 10 seconds by default, but can
be overriden via C<$ENV{PERL_ANYEVENT_MAX_SIGNAL_LATENCY}> or
C<$AnyEvent::MAX_SIGNAL_LATENCY> - see the L<ENVIRONMENT VARIABLES>
section for details.
All these problems can be avoided by installing the optional
L<Async::Interrupt> module, which works with most event loops. It will not
work with inherently broken event loops such as L<Event> or L<Event::Lib>
(and not with L<POE> currently). For those, you just have to suffer the
delays.
=head2 CHILD PROCESS WATCHERS
$w = AnyEvent->child (pid => <process id>, cb => <callback>);
You can also watch for a child process exit and catch its exit status.
The child process is specified by the C<pid> argument (on some backends,
using C<0> watches for any child process exit, on others this will
croak). The watcher will be triggered only when the child process has
finished and an exit status is available, not on any trace events
(stopped/continued).
The callback will be called with the pid and exit status (as returned by
waitpid), so unlike other watcher types, you I<can> rely on child watcher
callback arguments.
This watcher type works by installing a signal handler for C<SIGCHLD>,
and since it cannot be shared, nothing else should use SIGCHLD or reap
random child processes (waiting for specific child processes, e.g. inside
C<system>, is just fine).
There is a slight catch to child watchers, however: you usually start them
I<after> the child process was created, and this means the process could
have exited already (and no SIGCHLD will be sent anymore).
Not all event models handle this correctly (neither POE nor IO::Async do,
see their AnyEvent::Impl manpages for details), but even for event models
that I<do> handle this correctly, they usually need to be loaded before
the process exits (i.e. before you fork in the first place). AnyEvent's
pure perl event loop handles all cases correctly regardless of when you
start the watcher.
This means you cannot create a child watcher as the very first
thing in an AnyEvent program, you I<have> to create at least one
watcher before you C<fork> the child (alternatively, you can call
C<AnyEvent::detect>).
As most event loops do not support waiting for child events, they will be
emulated by AnyEvent in most cases, in which case the latency and race
problems mentioned in the description of signal watchers apply.
Example: fork a process and wait for it
my $done = AnyEvent->condvar;
# this forks and immediately calls exit in the child. this
# normally has all sorts of bad consequences for your parent,
# so take this as an example only. always fork and exec,
lib/AnyEvent.pm view on Meta::CPAN
Note that doing a blocking wait in a callback is not supported by any
event loop, that is, recursive invocation of a blocking C<< ->recv >> is
not allowed and the C<recv> call will C<croak> if such a condition is
detected. This requirement can be dropped by relying on L<Coro::AnyEvent>
, which allows you to do a blocking C<< ->recv >> from any thread
that doesn't run the event loop itself. L<Coro::AnyEvent> is loaded
automatically when L<Coro> is used with L<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 C<recv>, be executed in an
C<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 I<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 C<< ->recv >> never blocks by setting a callback and
only calling C<< ->recv >> from within that callback (or at a later
time). This will work even when the event loop does not support blocking
waits otherwise.
=item $bool = $cv->ready
Returns true when the condition is "true", i.e. whether C<send> or
C<croak> have been called.
=item $cb = $cv->cb ($cb->($cv))
This is a mutator function that returns the callback set (or C<undef> if
not) and optionally replaces it before doing so.
The callback will be called when the condition becomes "true", i.e. when
C<send> or C<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 C<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 C<undef>), so the condvar does not keep a reference to
the callback after invocation.
=back
=head1 SUPPORTED EVENT LOOPS/BACKENDS
The following backend classes are part of the AnyEvent distribution (every
class has its own manpage):
=over 4
=item 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.
=item 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).
=item 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.
=item 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 (L<Wx>) or L<Prima>.
B<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.
B<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 L<Prima> and L<Wx>, however, and will try to
load L<POE> when detecting them, in the hope that POE will pick them up,
in which case everything will be automatic.
=item 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
=back
=head1 GLOBAL VARIABLES AND FUNCTIONS
These are not normally required to use AnyEvent, but can be useful to
lib/AnyEvent.pm view on Meta::CPAN
It should use C<postpone>:
AnyEvent::postpone { $cb->(undef) }, return # signal error to callback, later
if $some_error_condition;
=item AnyEvent::log $level, $msg[, @args]
Log the given C<$msg> at the given C<$level>.
If L<AnyEvent::Log> is not loaded then this function makes a simple test
to see whether the message will be logged. If the test succeeds it will
load AnyEvent::Log and call C<AnyEvent::Log::log> - consequently, look at
the L<AnyEvent::Log> documentation for details.
If the test fails it will simply return. Right now this happens when a
numerical loglevel is used and it is larger than the level specified via
C<$ENV{PERL_ANYEVENT_VERBOSE}>.
If you want to sprinkle loads of logging calls around your code, consider
creating a logger callback with the C<AnyEvent::Log::logger> function,
which can reduce typing, codesize and can reduce the logging overhead
enourmously.
=item AnyEvent::fh_block $filehandle
=item AnyEvent::fh_unblock $filehandle
Sets blocking or non-blocking behaviour for the given filehandle.
=back
=head1 WHAT TO DO IN A MODULE
As a module author, you should C<use AnyEvent> and call AnyEvent methods
freely, but you should not load a specific event module or rely on it.
Be careful when you create watchers in the module body - AnyEvent will
decide which event module to use as soon as the first method is called, so
by calling AnyEvent in your module body you force the user of your module
to load the event module first.
Never call C<< ->recv >> on a condition variable unless you I<know> that
the C<< ->send >> method has been called on it already. This is
because it will stall the whole program, and the whole point of using
events is to stay interactive.
It is fine, however, to call C<< ->recv >> when the user of your module
requests it (i.e. if you create a http request object ad have a method
called C<results> that returns the results, it may call C<< ->recv >>
freely, as the user of your module knows what she is doing. Always).
=head1 WHAT TO DO IN THE MAIN PROGRAM
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 C<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
C<AnyEvent::Loop> module, which gives you similar behaviour
everywhere, but letting AnyEvent chose the model is generally better.
=head2 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.
=head1 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
L<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 :)
=over 4
=item L<AnyEvent::Util> (part of the AnyEvent distribution)
Contains various utility functions that replace often-used blocking
functions such as C<inet_aton> with event/callback-based versions.
=item L<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.
=item L<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 L<AnyEvent::TLS>).
lib/AnyEvent.pm view on Meta::CPAN
The rationale for this is that AnyEvent users usually do not really depend
on SIGPIPE delivery (which is purely an optimisation for shell use, or
badly-written programs), but C<SIGPIPE> can cause spurious and rare
program exits as a lot of people do not expect C<SIGPIPE> when writing to
some random socket.
The rationale for installing a no-op handler as opposed to ignoring it is
that this way, the handler will be restored to defaults on exec.
Feel free to install your own handler, or reset it to defaults.
=back
=cut
undef $SIG{CHLD}
if $SIG{CHLD} eq 'IGNORE';
$SIG{PIPE} = sub { }
unless defined $SIG{PIPE};
=head1 RECOMMENDED/OPTIONAL MODULES
One of AnyEvent's main goals is to be 100% Pure-Perl(tm): only perl (and
its built-in modules) are required to use it.
That does not mean that AnyEvent won't take advantage of some additional
modules if they are installed.
This section explains which additional modules will be used, and how they
affect AnyEvent's operation.
=over 4
=item L<Async::Interrupt>
This slightly arcane module is used to implement fast signal handling: To
my knowledge, there is no way to do completely race-free and quick
signal handling in pure perl. To ensure that signals still get
delivered, AnyEvent will start an interval timer to wake up perl (and
catch the signals) with some delay (default is 10 seconds, look for
C<$AnyEvent::MAX_SIGNAL_LATENCY>).
If this module is available, then it will be used to implement signal
catching, which means that signals will not be delayed, and the event loop
will not be interrupted regularly, which is more efficient (and good for
battery life on laptops).
This affects not just the pure-perl event loop, but also other event loops
that have no signal handling on their own (e.g. Glib, Tk, Qt).
Some event loops (POE, Event, Event::Lib) offer signal watchers natively,
and either employ their own workarounds (POE) or use AnyEvent's workaround
(using C<$AnyEvent::MAX_SIGNAL_LATENCY>). Installing L<Async::Interrupt>
does nothing for those backends.
=item L<EV>
This module isn't really "optional", as it is simply one of the backend
event loops that AnyEvent can use. However, it is simply the best event
loop available in terms of features, speed and stability: It supports
the AnyEvent API optimally, implements all the watcher types in XS, does
automatic timer adjustments even when no monotonic clock is available,
can take avdantage of advanced kernel interfaces such as C<epoll> and
C<kqueue>, and is the fastest backend I<by far>. You can even embed
L<Glib>/L<Gtk2> in it (or vice versa, see L<EV::Glib> and L<Glib::EV>).
If you only use backends that rely on another event loop (e.g. C<Tk>),
then this module will do nothing for you.
=item L<Guard>
The guard module, when used, will be used to implement
C<AnyEvent::Util::guard>. This speeds up guards considerably (and uses a
lot less memory), but otherwise doesn't affect guard operation much. It is
purely used for performance.
=item L<JSON> and L<JSON::XS>
One of these modules is required when you want to read or write JSON data
via L<AnyEvent::Handle>. L<JSON> is also written in pure-perl, but can take
advantage of the ultra-high-speed L<JSON::XS> module when it is installed.
=item L<Net::SSLeay>
Implementing TLS/SSL in Perl is certainly interesting, but not very
worthwhile: If this module is installed, then L<AnyEvent::Handle> (with
the help of L<AnyEvent::TLS>), gains the ability to do TLS/SSL.
=item L<Time::HiRes>
This module is part of perl since release 5.008. It will be used when the
chosen event library does not come with a timing source of its own. The
pure-perl event loop (L<AnyEvent::Loop>) will additionally load it to
try to use a monotonic clock for timing stability.
=item L<AnyEvent::AIO> (and L<IO::AIO>)
The default implementation of L<AnyEvent::IO> is to do I/O synchronously,
stopping programs while they access the disk, which is fine for a lot of
programs.
Installing AnyEvent::AIO (and its IO::AIO dependency) makes it switch to
a true asynchronous implementation, so event processing can continue even
while waiting for disk I/O.
=back
=head1 FORK
Most event libraries are not fork-safe. The ones who are usually are
because they rely on inefficient but fork-safe C<select> or C<poll> calls
- higher performance APIs such as BSD's kqueue or the dreaded Linux epoll
are usually badly thought-out hacks that are incompatible with fork in
one way or another. Only L<EV> is fully fork-aware and ensures that you
continue event-processing in both parent and child (or both, if you know
what you are doing).
This means that, in general, you cannot fork and do event processing in
( run in 0.883 second using v1.01-cache-2.11-cpan-39bf76dae61 )