AnyEvent

 view release on metacpan or  search on metacpan

lib/AnyEvent.pm  view on Meta::CPAN

=head1 NAME

AnyEvent - the DBI of event loop programming

EV, Event, Glib, Tk, UV, Perl, Event::Lib, Irssi, rxvt-unicode, IO::Async,
Qt, FLTK and POE are various supported event loops/environments.

=head1 SYNOPSIS

   use AnyEvent;

   # if you prefer function calls, look at the AE manpage for
   # an alternative API.

   # file handle or descriptor readable
   my $w = AnyEvent->io (fh => $fh, poll => "r", cb => sub { ...  });

   # one-shot or repeating timers
   my $w = AnyEvent->timer (after => $seconds, cb => sub { ...  });
   my $w = AnyEvent->timer (after => $seconds, interval => $seconds, cb => ...);

   print AnyEvent->now;  # prints current event loop time
   print AnyEvent->time; # think Time::HiRes::time or simply CORE::time.

   # POSIX signal
   my $w = AnyEvent->signal (signal => "TERM", cb => sub { ... });

   # child process exit
   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 });

=head1 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
L<AnyEvent::Intro> manpage.

=head1 SUPPORT

An FAQ document is available as L<AnyEvent::FAQ>.

There also is a mailinglist for discussing all things AnyEvent, and an IRC
channel, too.

See the AnyEvent project page at the B<Schmorpforge Ta-Sa Software
Repository>, at L<http://anyevent.schmorp.de>, for more info.

=head1 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 I<compatible>, AnyEvent is I<free of
policy> and AnyEvent is I<small and efficient>.

lib/AnyEvent.pm  view on Meta::CPAN


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
write AnyEvent extension modules.

=over 4

=item $AnyEvent::MODEL

Contains C<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 C<AnyEvent::Impl::xxx> modules, but can be any other class in the
case AnyEvent has been extended at runtime (e.g. in I<rxvt-unicode> it
will be C<urxvt::anyevent>).

=item AnyEvent::detect

Returns C<$AnyEvent::MODEL>, forcing autodetection of the event model
if necessary. You should only call this function right before you would
have created an AnyEvent watcher anyway, that is, as late as possible at
runtime, and not e.g. during initialisation of your module.

The effect of calling this function is as if a watcher had been created
(specifically, actions that happen "when the first watcher is created"
happen when calling detetc as well).

If you need to do some initialisation before AnyEvent watchers are
created, use C<post_detect>.

=item $guard = AnyEvent::post_detect { BLOCK }

Arranges for the code block to be executed as soon as the event model is
autodetected (or immediately if that has already happened).

The block will be executed I<after> the actual backend has been detected
(C<$AnyEvent::MODEL> is set), so it is possible to do some initialisation
only when AnyEvent is actually initialised - see the sources of
L<AnyEvent::AIO> to see how this is used.

The most common usage is to create some global watchers, without forcing
event module detection too early. For example, L<AnyEvent::AIO> creates
and installs the global L<IO::AIO> watcher in a C<post_detect> block to
avoid autodetecting the event module at load time.

If called in scalar or list context, then it creates and returns an object
that automatically removes the callback again when it is destroyed (or
C<undef> when the hook was immediately executed). See L<AnyEvent::AIO> for
a case where this is useful.

Example: Create a watcher for the IO::AIO module and store it in
C<$WATCHER>, but do so only do so after the event loop is initialised.

   our WATCHER;

   my $guard = AnyEvent::post_detect {
      $WATCHER = AnyEvent->io (fh => IO::AIO::poll_fileno, poll => 'r', cb => \&IO::AIO::poll_cb);
   };

   # the ||= is important in case post_detect immediately runs the block,
   # as to not clobber the newly-created watcher. assigning both watcher and
   # post_detect guard to the same variable has the advantage of users being
   # able to just C<undef $WATCHER> if the watcher causes them grief.

   $WATCHER ||= $guard;

=item @AnyEvent::post_detect

This is a lower level interface then C<AnyEvent::post_detect> (the
function). This variable is mainly useful for modules that can do
something useful when AnyEvent is used and thus want to know when it
is initialised, but do not need to even load it by default. This array
provides the means to hook into AnyEvent passively, without loading it.

lib/AnyEvent.pm  view on Meta::CPAN

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

=head1 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 event module and the package name of the interface to use onto
C<@AnyEvent::REGISTRY>. You can do that before and even without loading
AnyEvent, so it is reasonably cheap.

Example:

   push @AnyEvent::REGISTRY, [urxvt => urxvt::anyevent::];

This tells AnyEvent to (literally) use the C<urxvt::anyevent::>
package/class when it finds the C<urxvt> package/module is already loaded.

When AnyEvent is loaded and asked to find a suitable event model, it
will first check for the presence of urxvt by trying to C<use> the
C<urxvt::anyevent> module.

The class should provide implementations for all watcher types. See
L<AnyEvent::Impl::EV> (source code), L<AnyEvent::Impl::Glib> (Source code)
and so on for actual examples. Use C<perldoc -m AnyEvent::Impl::Glib> to
see the sources.

If you don't provide C<signal> and C<child> watchers than AnyEvent will
provide suitable (hopefully) replacements.

The above example isn't fictitious, the I<rxvt-unicode> (a.k.a. urxvt)
terminal emulator uses the above line as-is. An interface isn't included
in AnyEvent because it doesn't make sense outside the embedded interpreter
inside I<rxvt-unicode>, and it is updated and maintained as part of the
I<rxvt-unicode> distribution.

I<rxvt-unicode> also cheats a bit by not providing blocking access to
condition variables: code blocking while waiting for a condition will
C<die>. This still works with most modules/usages, and blocking calls must
not be done in an interactive application, so it makes sense.

=head1 EXAMPLE PROGRAM

The following program uses an I/O watcher to read data from STDIN, a timer
to display a message once per second, and a condition variable to quit the
program when the user enters quit:

   use AnyEvent;

   my $cv = AnyEvent->condvar;

   my $io_watcher = AnyEvent->io (
      fh   => \*STDIN,
      poll => 'r',
      cb   => sub {
         warn "io event <$_[0]>\n";   # will always output <r>
         chomp (my $input = <STDIN>); # read a line
         warn "read: $input\n";       # output what has been read
         $cv->send if $input =~ /^q/i; # quit program if /^q/i
      },
   );

   my $time_watcher = AnyEvent->timer (after => 1, interval => 1, cb => sub {
      warn "timeout\n"; # print 'timeout' at most every second
   });

   $cv->recv; # wait until user enters /^q/i

=head1 REAL-WORLD EXAMPLE

Consider the L<Net::FCP> module. It features (among others) the following
API calls, which are to freenet what HTTP GET requests are to http:

   my $data = $fcp->client_get ($url); # blocks

   my $transaction = $fcp->txn_client_get ($url); # does not block
   $transaction->cb ( sub { ... } ); # set optional result callback
   my $data = $transaction->result; # possibly blocks

The C<client_get> method works like C<LWP::Simple::get>: it requests the
given URL and waits till the data has arrived. It is defined to be:

   sub client_get { $_[0]->txn_client_get ($_[1])->result }

And in fact is automatically generated. This is the blocking API of
L<Net::FCP>, and it works as simple as in any other, similar, module.

More complicated is C<txn_client_get>: It only creates a transaction
(completion, result, ...) object and initiates the transaction.

   my $txn = bless { }, Net::FCP::Txn::;

It also creates a condition variable that is used to signal the completion
of the request:

   $txn->{finished} = AnyAvent->condvar;



( run in 0.733 second using v1.01-cache-2.11-cpan-d7f47b0818f )