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 _write_watches => (is => 'ro', default => sub { {} });
15 has _write_select => (is => 'ro', default => sub { IO::Select->new });
17 has _timers => (is => 'ro', default => sub { [] });
20 my ($self, $new_loop) = @_;
21 foreach my $fh ($self->_read_select->handles) {
24 on_read_ready => $self->_read_watches->{$fh}
27 foreach my $fh ($self->_write_select->handles) {
30 on_write_ready => $self->_write_watches->{$fh}
36 my ($self, %watch) = @_;
37 my $fh = $watch{handle};
38 if (my $cb = $watch{on_read_ready}) {
39 $self->_read_select->add($fh);
40 $self->_read_watches->{$fh} = $cb;
42 if (my $cb = $watch{on_write_ready}) {
43 $self->_write_select->add($fh);
44 $self->_write_watches->{$fh} = $cb;
50 my ($self, %watch) = @_;
51 my $fh = $watch{handle};
52 if ($watch{on_read_ready}) {
53 $self->_read_select->remove($fh);
54 delete $self->_read_watches->{$fh};
56 if ($watch{on_write_ready}) {
57 $self->_write_select->remove($fh);
58 delete $self->_write_watches->{$fh};
64 my ($self, %watch) = @_;
65 my $at = $watch{at} || do {
66 die "watch_time requires at or after" unless my $after = $watch{after};
69 die "watch_time requires code" unless my $code = $watch{code};
70 my $timers = $self->_timers;
71 my $new = [ $at => $code ];
72 @{$timers} = sort { $a->[0] <=> $b->[0] } @{$timers}, $new;
78 @$_ = grep !($_ eq $id), @$_ for $self->_timers;
84 my $read = $self->_read_watches;
85 my $write = $self->_write_watches;
86 my ($readable, $writeable) = IO::Select->select(
87 $self->_read_select, $self->_write_select, undef, 0.5
89 # I would love to trap errors in the select call but IO::Select doesn't
90 # differentiate between an error and a timeout.
92 foreach my $fh (@$readable) {
93 $read->{$fh}() if $read->{$fh};
95 foreach my $fh (@$writeable) {
96 $write->{$fh}() if $write->{$fh};
98 my $timers = $self->_timers;
100 while (@$timers and $timers->[0][0] <= $now) {
101 (shift @$timers)->[1]->();
108 $self->{want_running}++;
111 sub run_while_wanted {
113 $self->loop_once while $self->{want_running};
119 $self->{want_running}-- if $self->{want_running};
124 local $self->{is_running} = 1;
125 while ($self->is_running) {