The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

Event - Event loop processing

WARNING

THIS IS EXPERIMENTAL AND IS LIKELY TO CHANGE BEFORE BEING DECLARED STABLE AS GRANITE.

Thank you for your patience.

SYNOPSIS

 use Event qw(loop unloop);
 
 # initialize application
 Event->type(callback => sub { ... },
             typespecific => 1
            );
    
 my $ret = loop();
    
 # and some callback will call
 unloop('ok');

DESCRIPTION

The Event module provide a central facility to watch for various types of events and invoke a callback when these events occur. The key idea is to delay the handling of events so they can be dispatched in order of priority and also when it is known to be safe for callbacks to execute.

Events (the occurance of such) are handled by event watchers. The creation and configuration of event watchers is the primary topic of the rest of this document.

The following functions control and interrogate the event loop as a whole:

$result = loop()

Will enter a loop that calls one_event() until unloop() is called. The argument passed to unloop() is the return value of loop(). Loops can be nested.

unloop($result)

Make the inner-most loop() return with $result.

unloop_all()

Cause all pending loop()s to return immediately. This is not implemented with an exception. It works by effectly calling unloop(undef) for each pending loop.

one_event([$timeout])

If any events have happened, invoke the corresponding callback of the highest priority event. If no event has happened yet, block until forever or until $timeout.

all_events()

Return a list of all events created (including cancelled events).

all_running()

Return a list of all events running inside its callback at the moment. This can be more than one event!

all_queued()

Return all events queued in order of priority.

EVENT WATCHER CONSTRUCTORS

All watchers are constructed in one of the following ways:

  $w = Event->type( [-attr1 => $value,]... );
 

or

  use Event::type;
  $w = Event::type( [-attr1 => $value,]...);

Where type is substituted with the kind of watcher. Built in types include: idle, io, timer, watchvar, signal, and process.

The new watcher object is returned initialized with the attributes passed to the constructor. The watcher is already active. More precisely, the watcher object is "started" and already waiting for events (see $event-start> below).

SHARED WATCHER ATTRIBUTES

Watchers are configured with attributes (also called properties). This is a fancy way of saying that a watcher object works like hash reference. For example:

   $watcher->{callback} = \&some_code;
   $watcher->{-callback} = \&some_code;  # same thing

   print "$watcher->{-count} events happened; Wow!\n";

The key's dash (-) prefix is optional.

The following attributes are supported by all types of watchers. Most watchers types also offer additional attributes.

-id => $int

An integer that identifies this event. This attribute is read-only.

-callback => \&code
-callback => [$class_or_object, $method]

The function or method to call when an event happens. The callback is invoked with a reference to the $event as its only additional argument.

-count => $int

The number of times this event has happened since last time the callback was invoked. This attribute is read-only. It is reset to zero when the callback completes.

-priority => $int

The priority is used to order events queued for processing. Available priorities range from -1 to 6, inclusive. Lower numbers are higher priority (-1 is the highest priority, 6 is the lowest). When multiple events have happened, the event with the highest priority are serviced first.

A negative priority is interpreted to mean that the callback should be invoked immediately when the event happens. Use this with caution. While it may seem advantageous to use negative priorities, it defeats the purpose of having an event queue in the first place.

The -priority passed as argument to the event constructor is treated differently. It is an offset from the default priority of the event type.

-desc => $string

Some identifying name. If not passed to the constructor it will be initialized with some string that attempts to identify the location in the source code where the event object was constructed.

-flags => $bits

The flag attribute encodes some information about the state of an event. [XXX Fill in exact bits]

-repeat => $bool

The repeat flag controls if callback should be one-shot or if the watcher should continue waiting for new events of this kind occur. The default depends on the type of watcher. It defaults to TRUE for the io, signal, watchvar types.

-debug => $bool

Debugging can be activated per watcher. When debugging is enabled, $Event::DebugLevel is treated as one level higher for this watcher. A level of 1, 2, or 3 give progressively more noise on STDERR.

SHARED WATCHER METHODS

The following methods can be invoked on an event:

$watcher->start

Activate the watcher. Many constructors will automatically invoke $watcher->start.

$watcher->again

The same as the start method except in the case of events that do something special when they repeat. For example, repeating timers recalcuate their alarm time using their interval parameter.

$watcher->cancel

Don't look for any events any more. Note that the watcher can be reactivated by calling the start or again methods.

$watcher->now

Make the watcher callback trigger now. Note that the callback may or may not be run immediately depending upon its priority.

($runs, $elapse) = $watcher->stats( $sec )

Return statistics for the last $sec seconds of operation. Two numbers are returned: the number of times the callback has been invoked and the number of seconds spent within the callback. Also see NetServer::ProcessTop.

WATCHER TYPES

idle

The callback is invoked only if no other event is pending.

watchvar

Extra attribute: -variable => \$var

Triggered when the value of $var is changed.

timer

Extra attributes: -at => $time, -interval => $sec, -hard => $bool

The callback in invoked at the specified (-at) point in time. The $time and $sec arguments can be fractional seconds.

If -interval set, then the callback will be automatically resheduled after this amount of time. Due to lags in the event loop, the -interval timeout may already be in the past. If the -hard flag is set, then event will be queued for execution immediately. Otherwise, the new timeout will be calculated relative to the current time (this is the default).

The constructor also accepts an -after attribute as argument. The current time will be added to this value and stored in the object as the -at attribute.

io

Extra attributes: -handle => $fh, -events => "rwe", -got => "rwe"

The callback is invoked when the filehandle has data to be read, written, or pending exceptions. The -handle attribute specifies which filehandle to watch. It can be a glob, an IO::Handle object, or a file number (file descriptor). The -events specify which events to look for. It consist of a string with letters representing flags. "r" means to trigger when the handle is readable. "w" means to trigger when the handle is writable. "e" to trigger when the handle has pending exceptions.

When the callback is invoked, then the -got attribute tell you which -events triggered. The -got attribute is read-only.

Note that it is your choice whether to have multiple watchers per filehandle or a single watcher that handles all event flavors.

signal

Extra attribute: -signal => $str

The callback will be invoked when the specified signal has been received by this process. The $str is a string like "INT", "QUIT",...

While you are welcome to handle the CHLD signal yourself, you can also use the process watcher type.

process

Extra attribute: -pid => $int

Callback is invoked when the process with the given PID exits. If no pid is given then callback will be invoked when any child process terminates that does not have it's own event handler.

semaphore

Not implemented.

msg

Not implemented.

SUPPORT

This extension is discussed on the perl-loop@perl.org mailing list.

ALSO SEE

Event::Advanced (to be written) and NetServer::ProcessTop

AUTHORS

Graham Barr <gbarr@pobox.com>, Joshua Pritikin <bitset@mindspring.com>

COPYRIGHT

Copyright © 1997-1998 Graham Barr & Joshua Nathaniel Pritikin. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

1 POD Error

The following errors were encountered while parsing the POD:

Around line 308:

Non-ASCII character seen before =encoding in '©'. Assuming CP1252