ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/Coro/Coro/Timer.pm
Revision: 1.85
Committed: Sun Jul 3 10:51:42 2011 UTC (12 years, 11 months ago) by root
Branch: MAIN
CVS Tags: rel-6_01
Changes since 1.84: +1 -1 lines
Log Message:
6.01

File Contents

# User Rev Content
1 root 1.1 =head1 NAME
2    
3 root 1.58 Coro::Timer - timers and timeouts, independent of any event loop
4 root 1.1
5     =head1 SYNOPSIS
6    
7 root 1.79 # This package is mostly obsoleted by Coro::AnyEvent.
8    
9 root 1.8 use Coro::Timer qw(sleep timeout);
10     # nothing exported by default
11    
12     sleep 10;
13 root 1.1
14     =head1 DESCRIPTION
15    
16 root 1.79 This package has been mostly obsoleted by L<Coro::AnyEvent>, the only
17     really useful function left in here is C<timeout>.
18 root 1.4
19 root 1.1 =over 4
20    
21     =cut
22    
23     package Coro::Timer;
24    
25 root 1.71 use common::sense;
26 root 1.1
27     use Carp ();
28 root 1.74 use base Exporter::;
29 root 1.1
30     use Coro ();
31 root 1.36 use Coro::AnyEvent ();
32 root 1.1
33 root 1.85 our $VERSION = 6.01;
34 root 1.71 our @EXPORT_OK = qw(timeout sleep);
35 root 1.1
36 root 1.79 # compatibility with older programs
37     *sleep = \&Coro::AnyEvent::sleep;
38    
39     =item $flag = timeout $seconds
40    
41     This function will wake up the current coroutine after $seconds seconds
42     and sets $flag to true (it is false initially). If $flag goes out
43     of scope earlier then nothing happens.
44 root 1.3
45 root 1.79 This is used by Coro itself to implement the C<timed_down>, C<timed_wait>
46     etc. primitives. It is used like this:
47 root 1.4
48     sub timed_wait {
49     my $timeout = Coro::Timer::timeout 60;
50    
51     while (condition false) {
52 root 1.34 Coro::schedule; # wait until woken up or timeout
53 root 1.4 return 0 if $timeout; # timed out
54     }
55 root 1.34
56 root 1.4 return 1; # condition satisfied
57     }
58 root 1.3
59     =cut
60    
61     sub timeout($) {
62     my $current = $Coro::current;
63 root 1.33 my $timeout;
64 root 1.79
65     bless [
66     \$timeout,
67     (AE::timer $_[0], 0, sub {
68     $timeout = 1;
69     $current->ready;
70     }),
71     ], "Coro::Timer::Timeout";
72 root 1.3 }
73    
74 root 1.33 package Coro::Timer::Timeout;
75 root 1.9
76 root 1.79 sub bool { ${ $_[0][0] } }
77 root 1.3
78     use overload 'bool' => \&bool, '0+' => \&bool;
79    
80 root 1.1 1;
81    
82     =back
83    
84     =head1 AUTHOR
85    
86 root 1.23 Marc Lehmann <schmorp@schmorp.de>
87 root 1.21 http://home.schmorp.de/
88 root 1.1
89     =cut
90