Yichun Zhang (章亦春)


Sim::Dispatcher - Event dispatcher for Sim


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


    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

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


    # Example 2: Dynamic (recursive) scheduling

    my ($count, $handler);

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


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.


$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.


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.


Reads the value of the simulation time.


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


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


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


Agent Zhang <agentzh@gmail.com>


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.


Sim::Clock, Sim.