1 package Object::Remote::MiniLoop;
4 use Time::HiRes qw(time);
7 # this is ro because we only actually set it using local in sub run
9 has is_running => (is => 'ro', clearer => 'stop');
11 has _read_watches => (is => 'ro', default => sub { {} });
12 has _read_select => (is => 'ro', default => sub { IO::Select->new });
14 has _timers => (is => 'ro', default => sub { [] });
17 my ($self, $new_loop) = @_;
18 foreach my $fh ($self->_read_select->handles) {
21 on_read_ready => $self->_read_watches->{$fh}
27 my ($self, %watch) = @_;
28 my $fh = $watch{handle};
29 if (my $cb = $watch{on_read_ready}) {
30 $self->_read_select->add($fh);
31 $self->_read_watches->{$fh} = $cb;
36 my ($self, %watch) = @_;
37 my $fh = $watch{handle};
38 if ($watch{on_read_ready}) {
39 $self->_read_select->remove($fh);
40 delete $self->_read_watches->{$fh};
46 my ($self, %watch) = @_;
47 my $at = $watch{at} || do {
48 die "watch_time requires at or after" unless my $after = $watch{after};
51 die "watch_time requires code" unless my $code = $watch{code};
52 my $timers = $self->_timers;
53 my $new = [ $at => $code ];
54 @{$timers} = sort { $a->[0] <=> $b->[0] } @{$timers}, $new;
60 @$_ = grep !($_ eq $id), @$_ for $self->_timers;
66 my $read = $self->_read_watches;
67 my ($readable) = IO::Select->select($self->_read_select, undef, undef, 0.5);
68 # I would love to trap errors in the select call but IO::Select doesn't
69 # differentiate between an error and a timeout.
71 foreach my $fh (@$readable) {
74 my $timers = $self->_timers;
76 while (@$timers and $timers->[0][0] <= $now) {
77 (shift @$timers)->[1]->();
84 $self->{want_running}++;
87 sub run_while_wanted {
89 $self->loop_once while $self->{want_running};
95 $self->{want_running}-- if $self->{want_running};
100 local $self->{is_running} = 1;
101 while ($self->is_running) {