AnyEvent

 view release on metacpan or  search on metacpan

README  view on Meta::CPAN

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.

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 });

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

README  view on Meta::CPAN

    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
        other class in the case AnyEvent has been extended at runtime (e.g.
        in *rxvt-unicode* it will be "urxvt::anyevent").

    AnyEvent::detect
        Returns $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 "post_detect".

    $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 *after* the actual backend has been
        detected ($AnyEvent::MODEL is set), so it is possible to do some
        initialisation only when AnyEvent is actually initialised - see the
        sources of 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, AnyEvent::AIO
        creates and installs the global IO::AIO watcher in a "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 "undef" when the hook was immediately executed). See
        AnyEvent::AIO for a case where this is useful.

        Example: Create a watcher for the IO::AIO module and store it in
        $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;

    @AnyEvent::post_detect
        This is a lower level interface then "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.

        Here is how it works: If there are any code references in this array
        (you can "push" to it before or after loading AnyEvent), then they

README  view on Meta::CPAN

        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
    event module and the package name of the interface to use onto
    @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 "urxvt::anyevent::"
    package/class when it finds the "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 "use" the
    "urxvt::anyevent" module.

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

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

    The above example isn't fictitious, the *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 *rxvt-unicode*, and it is updated and maintained as
    part of the *rxvt-unicode* distribution.

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

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

REAL-WORLD EXAMPLE
    Consider the 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 "client_get" method works like "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
    Net::FCP, and it works as simple as in any other, similar, module.

    More complicated is "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;

    It then creates a socket in non-blocking mode.



( run in 1.445 second using v1.01-cache-2.11-cpan-39bf76dae61 )