AnyEvent
view release on metacpan or search on metacpan
lib/AnyEvent.pm view on Meta::CPAN
my $w; $w = AnyEvent->io (fh => \*STDIN, poll => 'r', cb => sub {
chomp (my $input = <STDIN>);
warn "read: $input\n";
undef $w;
});
=head2 TIME WATCHERS
$w = AnyEvent->timer (after => <seconds>, cb => <callback>);
$w = AnyEvent->timer (
after => <fractional_seconds>,
interval => <fractional_seconds>,
cb => <callback>,
);
You can create a time watcher by calling the C<< AnyEvent->timer >>
method with the following mandatory arguments:
C<after> specifies after how many seconds (fractional values are
supported) the callback should be invoked. C<cb> is the callback to invoke
in that case.
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 time watcher callbacks.
The callback will normally be invoked only once. If you specify another
parameter, C<interval>, as a strictly positive number (> 0), then the
callback will be invoked regularly at that interval (in fractional
seconds) after the first invocation. If C<interval> is specified with a
false value, then it is treated as if it were not specified at all.
The callback will be rescheduled before invoking the callback, but no
attempt is made to avoid timer drift in most backends, so the interval is
only approximate.
Example: fire an event after 7.7 seconds.
my $w = AnyEvent->timer (after => 7.7, cb => sub {
warn "timeout\n";
});
# to cancel the timer:
undef $w;
Example 2: fire an event after 0.5 seconds, then roughly every second.
my $w = AnyEvent->timer (after => 0.5, interval => 1, cb => sub {
warn "timeout\n";
});
=head3 TIMING ISSUES
There are two ways to handle timers: based on real time (relative, "fire
in 10 seconds") and based on wallclock time (absolute, "fire at 12
o'clock").
While most event loops expect timers to specified in a relative way, they
use absolute time internally. This makes a difference when your clock
"jumps", for example, when ntp decides to set your clock backwards from
the wrong date of 2014-01-01 to 2008-01-01, a watcher that is supposed to
fire "after a second" might actually take six years to finally fire.
AnyEvent cannot compensate for this. The only event loop that is conscious
of these issues is L<EV>, which offers both relative (ev_timer, based
on true relative time) and absolute (ev_periodic, based on wallclock time)
timers.
AnyEvent always prefers relative timers, if available, matching the
AnyEvent API.
AnyEvent has two additional methods that return the "current time":
=over 4
=item AnyEvent->time
This returns the "current wallclock time" as a fractional number of
seconds since the Epoch (the same thing as C<time> or C<Time::HiRes::time>
return, and the result is guaranteed to be compatible with those).
It progresses independently of any event loop processing, i.e. each call
will check the system clock, which usually gets updated frequently.
=item AnyEvent->now
This also returns the "current wallclock time", but unlike C<time>, above,
this value might change only once per event loop iteration, depending on
the event loop (most return the same time as C<time>, above). This is the
time that AnyEvent's timers get scheduled against.
I<In almost all cases (in all cases if you don't care), this is the
function to call when you want to know the current time.>
This function is also often faster then C<< AnyEvent->time >>, and
thus the preferred method if you want some timestamp (for example,
L<AnyEvent::Handle> uses this to update its activity timeouts).
The rest of this section is only of relevance if you try to be very exact
with your timing; you can skip it without a bad conscience.
For a practical example of when these times differ, consider L<Event::Lib>
and L<EV> and the following set-up:
The event loop is running and has just invoked one of your callbacks at
time=500 (assume no other callbacks delay processing). In your callback,
you wait a second by executing C<sleep 1> (blocking the process for a
second) and then (at time=501) you create a relative timer that fires
after three seconds.
With L<Event::Lib>, C<< AnyEvent->time >> and C<< AnyEvent->now >> will
both return C<501>, because that is the current time, and the timer will
be scheduled to fire at time=504 (C<501> + C<3>).
With L<EV>, C<< AnyEvent->time >> returns C<501> (as that is the current
time), but C<< AnyEvent->now >> returns C<500>, as that is the time the
last event processing phase started. With L<EV>, your timer gets scheduled
to run at time=503 (C<500> + C<3>).
In one sense, L<Event::Lib> is more exact, as it uses the current time
lib/AnyEvent.pm view on Meta::CPAN
my $results = $cv->recv;
This code fragment supposedly pings a number of hosts and calls
C<send> after results for all then have have been gathered - in any
order. To achieve this, the code issues a call to C<begin> when it starts
each ping request and calls C<end> when it has received some result for
it. Since C<begin> and C<end> only maintain a counter, the order in which
results arrive is not relevant.
There is an additional bracketing call to C<begin> and C<end> outside the
loop, which serves two important purposes: first, it sets the callback
to be called once the counter reaches C<0>, and second, it ensures that
C<send> is called even when C<no> hosts are being pinged (the loop
doesn't execute once).
This is the general pattern when you "fan out" into multiple (but
potentially zero) subrequests: use an outer C<begin>/C<end> pair to set
the callback and ensure C<end> is called at least once, and then, for each
subrequest you start, call C<begin> and for each subrequest you finish,
call C<end>.
=back
=head3 METHODS FOR CONSUMERS
These methods should only be used by the consuming side, i.e. the
code awaits the condition.
=over 4
=item $cv->recv
Wait (blocking if necessary) until the C<< ->send >> or C<< ->croak
>> methods have been called on C<$cv>, while servicing other watchers
normally.
You can only wait once on a condition - additional calls are valid but
will return immediately.
If an error condition has been set by calling C<< ->croak >>, then this
function will call C<croak>.
In list context, all parameters passed to C<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 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.
lib/AnyEvent.pm view on Meta::CPAN
C<AnyEvent::Socket::tcp_connect>:
# start a connection attempt unless one is active
$self->{connect_guard} ||= AnyEvent::Socket::tcp_connect "www.example.net", 80, sub {
delete $self->{connect_guard};
...
};
Imagine that this function could instantly call the callback, for
example, because it detects an obvious error such as a negative port
number. Invoking the callback before the function returns causes problems
however: the callback will be called and will try to delete the guard
object. But since the function hasn't returned yet, there is nothing to
delete. When the function eventually returns it will assign the guard
object to C<< $self->{connect_guard} >>, where it will likely never be
deleted, so the program thinks it is still trying to connect.
This is where C<AnyEvent::postpone> should be used. Instead of calling the
callback directly on error:
$cb->(undef), return # signal error to callback, BAD!
if $some_error_condition;
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>).
=item L<AnyEvent::DNS> (part of the AnyEvent distribution)
Provides rich asynchronous DNS resolver capabilities.
=item L<AnyEvent::HTTP>, L<AnyEvent::IRC>, L<AnyEvent::XMPP>, L<AnyEvent::GPSD>, L<AnyEvent::IGS>, L<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
lib/AnyEvent.pm view on Meta::CPAN
Can be set to C<0>, C<1> or C<2> and enables wrapping of all watchers for
debugging purposes. See C<AnyEvent::Debug::wrap> for details.
=item C<PERL_ANYEVENT_MODEL>
This can be used to specify the event model to be used by AnyEvent, before
auto detection and -probing kicks in.
It normally is a string consisting entirely of ASCII letters (e.g. C<EV>
or C<IOAsync>). The string C<AnyEvent::Impl::> gets prepended and the
resulting module name is loaded and - if the load was successful - used as
event model backend. If it fails to load then AnyEvent will proceed with
auto detection and -probing.
If the string ends with C<::> instead (e.g. C<AnyEvent::Impl::EV::>) then
nothing gets prepended and the module name is used as-is (hint: C<::> at
the end of a string designates a module name and quotes it appropriately).
For example, to force the pure perl model (L<AnyEvent::Loop::Perl>) you
could start your program like this:
PERL_ANYEVENT_MODEL=Perl perl ...
=item C<PERL_ANYEVENT_IO_MODEL>
The current file I/O model - see L<AnyEvent::IO> for more info.
At the moment, only C<Perl> (small, pure-perl, synchronous) and
C<IOAIO> (truly asynchronous) are supported. The default is C<IOAIO> if
L<AnyEvent::AIO> can be loaded, otherwise it is C<Perl>.
=item C<PERL_ANYEVENT_PROTOCOLS>
Used by both L<AnyEvent::DNS> and L<AnyEvent::Socket> to determine preferences
for IPv4 or IPv6. The default is unspecified (and might change, or be the result
of auto probing).
Must be set to a comma-separated list of protocols or address families,
current supported: C<ipv4> and C<ipv6>. Only protocols mentioned will be
used, and preference will be given to protocols mentioned earlier in the
list.
This variable can effectively be used for denial-of-service attacks
against local programs (e.g. when setuid), although the impact is likely
small, as the program has to handle connection and other failures anyways.
Examples: C<PERL_ANYEVENT_PROTOCOLS=ipv4,ipv6> - prefer IPv4 over IPv6,
but support both and try to use both. C<PERL_ANYEVENT_PROTOCOLS=ipv4>
- only support IPv4, never try to resolve or contact IPv6
addresses. C<PERL_ANYEVENT_PROTOCOLS=ipv6,ipv4> support either IPv4 or
IPv6, but prefer IPv6 over IPv4.
=item C<PERL_ANYEVENT_HOSTS>
This variable, if specified, overrides the F</etc/hosts> file used by
L<AnyEvent::Socket>C<::resolve_sockaddr>, i.e. hosts aliases will be read
from that file instead.
=item C<PERL_ANYEVENT_EDNS0>
Used by L<AnyEvent::DNS> to decide whether to use the EDNS0 extension for
DNS. This extension is generally useful to reduce DNS traffic, especially
when DNSSEC is involved, but some (broken) firewalls drop such DNS
packets, which is why it is off by default.
Setting this variable to C<1> will cause L<AnyEvent::DNS> to announce
EDNS0 in its DNS requests.
=item C<PERL_ANYEVENT_MAX_FORKS>
The maximum number of child processes that C<AnyEvent::Util::fork_call>
will create in parallel.
=item C<PERL_ANYEVENT_MAX_OUTSTANDING_DNS>
The default value for the C<max_outstanding> parameter for the default DNS
resolver - this is the maximum number of parallel DNS requests that are
sent to the DNS server.
=item C<PERL_ANYEVENT_MAX_SIGNAL_LATENCY>
Perl has inherently racy signal handling (you can basically choose between
losing signals and memory corruption) - pure perl event loops (including
C<AnyEvent::Loop>, when C<Async::Interrupt> isn't available) therefore
have to poll regularly to avoid losing signals.
Some event loops are racy, but don't poll regularly, and some event loops
are written in C but are still racy. For those event loops, AnyEvent
installs a timer that regularly wakes up the event loop.
By default, the interval for this timer is C<10> seconds, but you can
override this delay with this environment variable (or by setting
the C<$AnyEvent::MAX_SIGNAL_LATENCY> variable before creating signal
watchers).
Lower values increase CPU (and energy) usage, higher values can introduce
long delays when reaping children or waiting for signals.
The L<AnyEvent::Async> module, if available, will be used to avoid this
polling (with most event loops).
=item C<PERL_ANYEVENT_RESOLV_CONF>
The absolute path to a F<resolv.conf>-style file to use instead of
F</etc/resolv.conf> (or the OS-specific configuration) in the default
resolver, or the empty string to select the default configuration.
=item C<PERL_ANYEVENT_CA_FILE>, C<PERL_ANYEVENT_CA_PATH>.
When neither C<ca_file> nor C<ca_path> was specified during
L<AnyEvent::TLS> context creation, and either of these environment
variables are nonempty, they will be used to specify CA certificate
locations instead of a system-dependent default.
=item C<PERL_ANYEVENT_AVOID_GUARD> and C<PERL_ANYEVENT_AVOID_ASYNC_INTERRUPT>
When these are set to C<1>, then the respective modules are not
loaded. Mostly good for testing AnyEvent itself.
=back
( run in 0.915 second using v1.01-cache-2.11-cpan-39bf76dae61 )