NAME

Sim::Dispatcher - Event dispatcher for Sim

VERSION

This document describes Sim::Dispatcher 0.03 released on June 2, 2007.

SYNOPSIS

use Sim::Dispatcher;
use Sim::Clock;

my $clock = Sim::Clock->new;
# you can also use your own Clock instance here
my $engine = Sim::Dispatcher->new(clock => $clock);

# Example 1: Static scheduling

$engine->schedule(
   0 => sub { print $engine->now, ": morning!\n" },
   1 => sub { print $engine->now, ": afternoon!\n" },
   5 => sub { print $engine->now, ": night!\n" },
);
$engine->run( duration => 50 );
# or Sim::Dispatcher->run( fires => 5 );

$engine->reset();

# Example 2: Dynamic (recursive) scheduling

my ($count, $handler);

# event handler:
$handler = sub {
    $count++;
    my $time_for_next = $engine->now() + 2;
    $engine->schedule(
        $time_for_next => $handler,
    );
};
# only schedule the "seed" event
$engine->schedule(
    0.5 => $handler,
);
$engine->run( fires => 5 );
print "count: $count\n";  # 5
print "now: ", $engine->now(), "\n";  # 8

DESCRIPTION

This class implements the most important component in the whole Sim library, the event dispatcher. Basically, every activites should be coordinated by this dispatcher. Every other objects in a simulator either register an event scheduled to happen at some point in the "future", or iterate through the dispatching steps.

METHODS

$obj = Sim::Dispatcher->new( clock => $clock)

Object constructor accepting one mandatory named argument $clock which is an instance of classes like Sim::Clock.

$obj->schedule( $time => $handle, ... )

You can use this method to register events scheduled for the future, where $time is the timestamp and $handle is an anonymous sub which will be invoked by the dispatcher when the simulation time is at $time.

$obj->run( duration => $time, fires => $count )

Runs the dispatcher according to the time duration and event firing count. both of these named parameters are optional. When none is specified, fires => 100_000_000 will be assumed.

$obj->fire_next()

This method allows you to iterate through the dispatcher running process yourself. You should only call fire_next by hand if you've found the limitation criteria given by the run method can't fit your needs.

$obj->now()

Reads the value of the simulation time.

$obj->time_of_next()

Gets the timestamp of the next (or nearest) coming event, which is always a bit greater or equal to "now".

$obj->reset()

Clears the internal event queue of the dispatcher and resets the internal simulation clock too.

CONCURRENCY ISSUES

If two events have exactly the same timestamp, say, 1.5, then the one registered earlier will be fired first.

AUTHOR

Agent Zhang <agentzh@gmail.com>

COPYRIGHT

Copyright 2006, 2007 by Agent Zhang. All rights reserved.

This library is free software; you can modify and/or modify it under the same terms as Perl itself.

SEE ALSO

Sim::Clock, Sim.