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 |
print "hihohihoh ($timer, $timer->{_coro_state})\n"; |
72 |
print "hihohihoy $Coro::current\n"; |
73 |
use Devel::Peek; |
74 |
#Dump($timer); |
75 |
undef $timer; |
76 |
print "hihohihox $Coro::current\n"; |
77 |
}; |
78 |
$timer->prio(Coro::PRIO_MIN); |
79 |
$timer->ready; |
80 |
} |
81 |
|
82 |
$self; |
83 |
}; |
84 |
|
85 |
*cancel = sub { |
86 |
undef $_[0][1]; |
87 |
}; |
88 |
} |
89 |
|
90 |
=item $timer->cancel |
91 |
|
92 |
Cancel the timer (the callback will no longer be called). |
93 |
|
94 |
=cut |
95 |
|
96 |
1; |
97 |
|
98 |
=back |
99 |
|
100 |
=head1 AUTHOR |
101 |
|
102 |
Marc Lehmann <pcg@goof.com> |
103 |
http://www.goof.com/pcg/marc/ |
104 |
|
105 |
=cut |
106 |
|