AnyEvent
view release on metacpan or search on metacpan
watcher.
my $w; $w = AnyEvent->io (fh => \*STDIN, poll => 'r', cb => sub {
chomp (my $input = <STDIN>);
warn "read: $input\n";
undef $w;
});
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 "AnyEvent->timer" method
with the following mandatory arguments:
"after" specifies after how many seconds (fractional values are
supported) the callback should be invoked. "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, "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 "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";
});
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 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":
AnyEvent->time
This returns the "current wallclock time" as a fractional number of
seconds since the Epoch (the same thing as "time" or
"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.
AnyEvent->now
This also returns the "current wallclock time", but unlike "time",
above, this value might change only once per event loop iteration,
depending on the event loop (most return the same time as "time",
above). This is the time that AnyEvent's timers get scheduled
against.
*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 "AnyEvent->time", and thus
the preferred method if you want some timestamp (for example,
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
Event::Lib and 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 "sleep 1" (blocking the
process for a second) and then (at time=501) you create a relative
timer that fires after three seconds.
With Event::Lib, "AnyEvent->time" and "AnyEvent->now" will both
return 501, because that is the current time, and the timer will be
scheduled to fire at time=504 (501 + 3).
With EV, "AnyEvent->time" returns 501 (as that is the current time),
but "AnyEvent->now" returns 500, as that is the time the last event
processing phase started. With EV, your timer gets scheduled to run
at time=503 (500 + 3).
In one sense, Event::Lib is more exact, as it uses the current time
};
}
$cv->end;
...
my $results = $cv->recv;
This code fragment supposedly pings a number of hosts and calls
"send" after results for all then have have been gathered - in any
order. To achieve this, the code issues a call to "begin" when it
starts each ping request and calls "end" when it has received some
result for it. Since "begin" and "end" only maintain a counter, the
order in which results arrive is not relevant.
There is an additional bracketing call to "begin" and "end" outside
the loop, which serves two important purposes: first, it sets the
callback to be called once the counter reaches 0, and second, it
ensures that "send" is called even when "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 "begin"/"end" pair to
set the callback and ensure "end" is called at least once, and then,
for each subrequest you start, call "begin" and for each subrequest
you finish, call "end".
METHODS FOR CONSUMERS
These methods should only be used by the consuming side, i.e. the code
awaits the condition.
$cv->recv
Wait (blocking if necessary) until the "->send" or "->croak" methods
have been called on $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 "->croak", then this
function will call "croak".
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).
... }" idiom more useful.
To understand the usefulness of this function, consider a function
that asynchronously does something for you and returns some
transaction object or guard to let you cancel the operation. For
example, "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 "$self->{connect_guard}", where it will
likely never be deleted, so the program thinks it is still trying to
connect.
This is where "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 "postpone":
AnyEvent::postpone { $cb->(undef) }, return # signal error to callback, later
if $some_error_condition;
AnyEvent::log $level, $msg[, @args]
Log the given $msg at the given $level.
If 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 "AnyEvent::Log::log" -
consequently, look at the 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 $ENV{PERL_ANYEVENT_VERBOSE}.
If you want to sprinkle loads of logging calls around your code,
consider creating a logger callback with the "AnyEvent::Log::logger"
function, which can reduce typing, codesize and can reduce the
logging overhead enourmously.
AnyEvent::fh_block $filehandle
AnyEvent::fh_unblock $filehandle
Sets blocking or non-blocking behaviour for the given filehandle.
WHAT TO DO IN A MODULE
As a module author, you should "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 "->recv" on a condition variable unless you *know* that the
"->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 "->recv" when the user of your module
requests it (i.e. if you create a http request object ad have a method
called "results" that returns the results, it may call "->recv" freely,
as the user of your module knows what she is doing. Always).
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 "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
"PERL_ANYEVENT_DEBUG_WRAP"
Can be set to 0, 1 or 2 and enables wrapping of all watchers for
debugging purposes. See "AnyEvent::Debug::wrap" for details.
"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.
"EV" or "IOAsync"). The string "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 "::" instead (e.g. "AnyEvent::Impl::EV::")
then nothing gets prepended and the module name is used as-is (hint:
"::" at the end of a string designates a module name and quotes it
appropriately).
For example, to force the pure perl model (AnyEvent::Loop::Perl) you
could start your program like this:
PERL_ANYEVENT_MODEL=Perl perl ...
"PERL_ANYEVENT_IO_MODEL"
The current file I/O model - see AnyEvent::IO for more info.
At the moment, only "Perl" (small, pure-perl, synchronous) and
"IOAIO" (truly asynchronous) are supported. The default is "IOAIO"
if AnyEvent::AIO can be loaded, otherwise it is "Perl".
"PERL_ANYEVENT_PROTOCOLS"
Used by both AnyEvent::DNS and 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: "ipv4" and "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: "PERL_ANYEVENT_PROTOCOLS=ipv4,ipv6" - prefer IPv4 over
IPv6, but support both and try to use both.
"PERL_ANYEVENT_PROTOCOLS=ipv4" - only support IPv4, never try to
resolve or contact IPv6 addresses.
"PERL_ANYEVENT_PROTOCOLS=ipv6,ipv4" support either IPv4 or IPv6, but
prefer IPv6 over IPv4.
"PERL_ANYEVENT_HOSTS"
This variable, if specified, overrides the /etc/hosts file used by
AnyEvent::Socket"::resolve_sockaddr", i.e. hosts aliases will be
read from that file instead.
"PERL_ANYEVENT_EDNS0"
Used by 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 1 will cause AnyEvent::DNS to announce
EDNS0 in its DNS requests.
"PERL_ANYEVENT_MAX_FORKS"
The maximum number of child processes that
"AnyEvent::Util::fork_call" will create in parallel.
"PERL_ANYEVENT_MAX_OUTSTANDING_DNS"
The default value for the "max_outstanding" parameter for the
default DNS resolver - this is the maximum number of parallel DNS
requests that are sent to the DNS server.
"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 "AnyEvent::Loop", when "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 10 seconds, but you can
override this delay with this environment variable (or by setting
the $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 AnyEvent::Async module, if available, will be used to avoid this
polling (with most event loops).
"PERL_ANYEVENT_RESOLV_CONF"
The absolute path to a resolv.conf-style file to use instead of
/etc/resolv.conf (or the OS-specific configuration) in the default
resolver, or the empty string to select the default configuration.
"PERL_ANYEVENT_CA_FILE", "PERL_ANYEVENT_CA_PATH".
When neither "ca_file" nor "ca_path" was specified during
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.
"PERL_ANYEVENT_AVOID_GUARD" and "PERL_ANYEVENT_AVOID_ASYNC_INTERRUPT"
When these are set to 1, then the respective modules are not loaded.
Mostly good for testing AnyEvent itself.
SUPPLYING YOUR OWN EVENT MODEL INTERFACE
This is an advanced topic that you do not normally need to use AnyEvent
in a module. This section is only of use to event loop authors who want
to provide AnyEvent compatibility.
If you need to support another event library which isn't directly
supported by AnyEvent, you can supply your own interface to it by
pushing, before the first watcher gets created, the package name of the
( run in 1.052 second using v1.01-cache-2.11-cpan-39bf76dae61 )