… | |
… | |
33 | |
33 | |
34 | BEGIN { |
34 | BEGIN { |
35 | eval "use Time::HiRes 'time'"; |
35 | eval "use Time::HiRes 'time'"; |
36 | } |
36 | } |
37 | |
37 | |
38 | $VERSION = 0.533; |
38 | $VERSION = 0.6; |
39 | @EXPORT_OK = qw(timeout sleep); |
39 | @EXPORT_OK = qw(timeout sleep); |
40 | |
40 | |
41 | =item $flag = timeout $seconds; |
41 | =item $flag = timeout $seconds; |
42 | |
42 | |
43 | This function will wake up the current coroutine after $seconds |
43 | This function will wake up the current coroutine after $seconds |
… | |
… | |
68 | bless $self, Coro::timeout::; |
68 | bless $self, Coro::timeout::; |
69 | } |
69 | } |
70 | |
70 | |
71 | package Coro::timeout; |
71 | package Coro::timeout; |
72 | |
72 | |
73 | sub bool { !${${$_[0]}} } |
73 | sub bool { |
74 | sub DESTROY { ${${$_[0]}}->cancel } |
74 | !${${$_[0]}} |
|
|
75 | } |
|
|
76 | |
|
|
77 | sub DESTROY { |
|
|
78 | ${${$_[0]}}->cancel; |
|
|
79 | undef ${${$_[0]}}; # without this it leaks like hell. breaks the circular reference inside the closure |
|
|
80 | } |
75 | |
81 | |
76 | use overload 'bool' => \&bool, '0+' => \&bool; |
82 | use overload 'bool' => \&bool, '0+' => \&bool; |
77 | |
83 | |
78 | package Coro::Timer; |
84 | package Coro::Timer; |
79 | |
85 | |
… | |
… | |
84 | |
90 | |
85 | =cut |
91 | =cut |
86 | |
92 | |
87 | sub sleep { |
93 | sub sleep { |
88 | my $current = $Coro::current; |
94 | my $current = $Coro::current; |
89 | _new_timer(time + $_[0], sub { $current->ready }); |
95 | my $timer = _new_timer(time + $_[0], sub { $current->ready }); |
90 | Coro::schedule; |
96 | Coro::schedule; |
|
|
97 | $timer->cancel; |
91 | } |
98 | } |
92 | |
99 | |
93 | =item $timer = new Coro::Timer at/after => xxx, cb => \&yyy; |
100 | =item $timer = new Coro::Timer at/after => xxx, cb => \&yyy; |
94 | |
101 | |
95 | Create a new timer. |
102 | Create a new timer. |
… | |
… | |
143 | }; |
150 | }; |
144 | } |
151 | } |
145 | |
152 | |
146 | =item $timer->cancel |
153 | =item $timer->cancel |
147 | |
154 | |
148 | Cancel the timer (the callback will no longer be called). |
155 | Cancel the timer (the callback will no longer be called). This method MUST |
|
|
156 | be called to remove the timer from memory, otherwise it will never be |
|
|
157 | freed! |
149 | |
158 | |
150 | =cut |
159 | =cut |
151 | |
160 | |
152 | 1; |
161 | 1; |
153 | |
162 | |