1 |
root |
1.1 |
=head1 NAME |
2 |
|
|
|
3 |
|
|
Coro::Timer - simple timer package, independent of used event loops |
4 |
|
|
|
5 |
|
|
=head1 SYNOPSIS |
6 |
|
|
|
7 |
|
|
use Coro::Timer; |
8 |
|
|
|
9 |
|
|
=head1 DESCRIPTION |
10 |
|
|
|
11 |
|
|
This package implements a simple timer callback system which works |
12 |
|
|
independent of the event loop mechanism used. If no event mechanism is |
13 |
|
|
used, it is emulated. The C<Coro::Event> module overwrites functions with |
14 |
|
|
versions better suited. |
15 |
|
|
|
16 |
|
|
=over 4 |
17 |
|
|
|
18 |
|
|
=cut |
19 |
|
|
|
20 |
|
|
package Coro::Timer; |
21 |
|
|
|
22 |
|
|
no warnings qw(uninitialized); |
23 |
|
|
|
24 |
|
|
use Carp (); |
25 |
|
|
|
26 |
|
|
use Coro (); |
27 |
|
|
|
28 |
|
|
BEGIN { eval "use Time::HiRes 'time'" } |
29 |
|
|
|
30 |
|
|
$VERSION = 0.52; |
31 |
|
|
|
32 |
|
|
=item $timer = new Coro::Timer at/after => xxx, cb => \&yyy; |
33 |
|
|
|
34 |
|
|
Create a new timer. |
35 |
|
|
|
36 |
|
|
=cut |
37 |
|
|
|
38 |
|
|
sub new { |
39 |
|
|
my $class = shift; |
40 |
|
|
my %arg = @_; |
41 |
|
|
|
42 |
|
|
$arg{at} = time + delete $arg{after} if exists $arg{after}; |
43 |
|
|
|
44 |
|
|
_new_timer($class, $arg{at}, $arg{cb}); |
45 |
|
|
} |
46 |
|
|
|
47 |
|
|
my $timer; |
48 |
|
|
my @timer; |
49 |
|
|
|
50 |
|
|
unless ($override) { |
51 |
|
|
$override = 1; |
52 |
|
|
*_new_timer = sub { |
53 |
|
|
my $self = bless [$_[1], $_[2]], $_[0]; |
54 |
|
|
|
55 |
|
|
# my version of rapid prototyping. guys, use a real event module! |
56 |
|
|
@timer = sort { $a->[0] cmp $b->[0] } @timer, $self; |
57 |
|
|
|
58 |
|
|
unless ($timer) { |
59 |
|
|
$timer = new Coro sub { |
60 |
|
|
my $NOW = time; |
61 |
|
|
while (@timer) { |
62 |
|
|
Coro::cede; |
63 |
|
|
if ($NOW >= $timer[0][0]) { |
64 |
|
|
my $next = shift @timer; |
65 |
|
|
$next->[1] and $next->[1]->(); |
66 |
|
|
} else { |
67 |
|
|
select undef, undef, undef, $timer[0][0] - $NOW; |
68 |
|
|
$NOW = time; |
69 |
|
|
} |
70 |
|
|
}; |
71 |
|
|
undef $timer; |
72 |
|
|
}; |
73 |
|
|
$timer->prio(Coro::PRIO_MIN); |
74 |
|
|
$timer->ready; |
75 |
|
|
} |
76 |
|
|
|
77 |
|
|
$self; |
78 |
|
|
}; |
79 |
|
|
|
80 |
|
|
*cancel = sub { |
81 |
|
|
undef $_[0][1]; |
82 |
|
|
}; |
83 |
|
|
} |
84 |
|
|
|
85 |
|
|
=item $timer->cancel |
86 |
|
|
|
87 |
|
|
Cancel the timer (the callback will no longer be called). |
88 |
|
|
|
89 |
|
|
=cut |
90 |
|
|
|
91 |
|
|
1; |
92 |
|
|
|
93 |
|
|
=back |
94 |
|
|
|
95 |
|
|
=head1 AUTHOR |
96 |
|
|
|
97 |
|
|
Marc Lehmann <pcg@goof.com> |
98 |
|
|
http://www.goof.com/pcg/marc/ |
99 |
|
|
|
100 |
|
|
=cut |
101 |
|
|
|