ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/Coro/Coro/Timer.pm
Revision: 1.45
Committed: Tue Sep 23 00:02:20 2008 UTC (15 years, 8 months ago) by root
Branch: MAIN
CVS Tags: rel-4_747
Changes since 1.44: +1 -1 lines
Log Message:
4.747

File Contents

# Content
1 =head1 NAME
2
3 Coro::Timer - simple timer package, independent of used event loops
4
5 =head1 SYNOPSIS
6
7 use Coro::Timer qw(sleep timeout);
8 # nothing exported by default
9
10 sleep 10;
11
12 =head1 DESCRIPTION
13
14 This package implements a simple timer callback system which works
15 independent of the event loop mechanism used.
16
17 =over 4
18
19 =cut
20
21 package Coro::Timer;
22
23 no warnings;
24
25 use Carp ();
26 use Exporter;
27
28 use AnyEvent ();
29
30 use Coro ();
31 use Coro::AnyEvent ();
32
33 $VERSION = 4.747;
34 @EXPORT_OK = qw(timeout sleep);
35
36 =item $flag = timeout $seconds;
37
38 This function will wake up the current coroutine after $seconds
39 seconds and sets $flag to true (it is false initially). If $flag goes
40 out of scope earlier nothing happens. This is used to implement the
41 C<timed_down>, C<timed_wait> etc. primitives. It is used like this:
42
43 sub timed_wait {
44 my $timeout = Coro::Timer::timeout 60;
45
46 while (condition false) {
47 Coro::schedule; # wait until woken up or timeout
48 return 0 if $timeout; # timed out
49 }
50
51 return 1; # condition satisfied
52 }
53
54 =cut
55
56 # deep magic, expecially the double indirection :(:(
57 sub timeout($) {
58 my $current = $Coro::current;
59 my $timeout;
60 bless {
61 timer => AnyEvent->timer (after => $_[0], cb => sub {
62 $timeout = 1;
63 $current->ready;
64 }),
65 timeout => \$timeout,
66 }, "Coro::Timer::Timeout";
67 }
68
69 package Coro::Timer::Timeout;
70
71 sub bool { ${$_[0]{timeout}} }
72
73 use overload 'bool' => \&bool, '0+' => \&bool;
74
75 package Coro::Timer;
76
77 =item sleep $seconds
78
79 This function works like the built-in sleep, except maybe more precise
80 and, most important, without blocking other coroutines.
81
82 =cut
83
84 sub sleep {
85 my $current = $Coro::current;
86
87 my $timer = AnyEvent->timer (after => $_[0], cb => sub {
88 $current->ready;
89 undef $current;
90 });
91
92 do { &Coro::schedule } while $current;
93 }
94
95 1;
96
97 =back
98
99 =head1 AUTHOR
100
101 Marc Lehmann <schmorp@schmorp.de>
102 http://home.schmorp.de/
103
104 =cut
105