Mojo/IOLoop.pm

filter: Statementstmt 95.9% 143 / 149 Branchbran 86.9% 40 / 46 Conditioncond 72.0% 31 / 43 MC/DCmcdc 58.3% 14 / 24 Subroutinesub 93.1% 41 / 44 Podpod 100% 16 / 16 totaltotal 88.5% 285 / 322 CC 43 SCAR 12.0
CC
43
Cov
90%
_remove
8.0
subprocess
6.0
_out
6.0
CRAP 3.3
« Mojolicious/Plugin/EPRenderer.pm ↑ Summary Mojolicious/Command/prefork.pm »
1 package Mojo::IOLoop;
2 33 ▶use Mojo::Base 'Mojo::EventEmitter';
Subroutine BEGIN: called CC=1 SCAR=0.0
3  
4 # "Professor: Amy, technology isn't intrinsically good or evil. It's how it's
5 # used. Like the death ray."
6 33 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
7 33 ▶use Mojo::IOLoop::Client;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 33 ▶use Mojo::IOLoop::Server;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 33 ▶use Mojo::IOLoop::Stream;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 33 ▶use Mojo::IOLoop::Subprocess;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 33 ▶use Mojo::Reactor::Poll;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 33 ▶use Mojo::Util qw(md5_sum steady_time);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 33 ▶use Scalar::Util qw(blessed weaken);
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 33 ▶use constant DEBUG => $ENV{MOJO_IOLOOP_DEBUG} || 0;
Subroutine BEGIN: called CC=2 SCAR=7.1
Condition50%1/2
$ENV{'MOJO_IOLOOP_DEBUG'} || 0
l!l
033
MC/DC0%0/1
$ENV{'MOJO_IOLOOP_DEBUG'} || 0
$ENV{'MOJO_IOLOOP_DEBUG'}
Truth table50%1/2
A
A= $ENV{'MOJO_IOLOOP_DEBUG'}
Aresult
11
00
16  
17 33 has max_accepts => 0;
18 33 has max_connections => 1000;
19 51 ▶has reactor => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
20 51 my $class = Mojo::Reactor::Poll->detect;
21 51 warn "-- Reactor initialized ($class)\n" if DEBUG;
22 51 ▶ return $class->new->catch(sub { warn "@{[blessed $_[0]]}: $_[1]" });
Subroutine __ANON__: called CC=1 SCAR=0.0
23 33 };
24  
25 # Ignore PIPE signal
26 33 $SIG{PIPE} = 'IGNORE';
27  
28 # Initialize singleton reactor early
29 33 __PACKAGE__->singleton->reactor;
30  
31 113 ▶sub acceptor {
Subroutine acceptor: called CC=2 SCAR=6.9
Pod documented
32 113 my ($self, $acceptor) = (_instance(shift), @_);
33  
34 # Find acceptor for id
35 113 ▶ return $self->{acceptors}{$acceptor} unless ref $acceptor;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $acceptor 62 51 113
36  
37 # Connect acceptor with reactor
38 51 $self->{acceptors}{my $id = $self->_id} = $acceptor->reactor($self->reactor);
39  
40 # Allow new acceptor to get picked up
41 51 $self->_not_accepting->_maybe_accepting;
42  
43 51 return $id;
44 }
45  
46 39 ▶sub client {
Subroutine client: called CC=1 SCAR=0.0
Pod documented
47 39 my ($self, $cb) = (_instance(shift), pop);
48  
49 39 my $id = $self->_id;
50 39 my $client = $self->{out}{$id}{client} = Mojo::IOLoop::Client->new(reactor => $self->reactor);
51  
52 39 weaken $self;
53 $client->on(
54 39 ▶ connect => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
55 39 delete $self->{out}{$id}{client};
56 39 my $stream = Mojo::IOLoop::Stream->new(pop);
57 39 $self->_stream($stream => $id);
58 39 $self->$cb(undef, $stream);
59 }
60 39 );
61 0 ▶ $client->on(error => sub { $self->_remove($id); $self->$cb(pop, undef) });
Subroutine __ANON__: not called CC=1 SCAR=2.6
62 39 $client->connect(@_);
63  
64 39 return $id;
65 }
66  
67 616 ▶sub is_running { _instance(shift)->reactor->is_running }
Subroutine is_running: called CC=1 SCAR=0.0
Pod documented
68  
69 787 ▶sub next_tick {
Subroutine next_tick: called CC=1 SCAR=0.0
Pod documented
70 787 my ($self, $cb) = (_instance(shift), @_);
71 787 weaken $self;
72 787 ▶ return $self->reactor->next_tick(sub { $self->$cb });
Subroutine __ANON__: called CC=1 SCAR=0.0
73 }
74  
75 204 ▶sub one_tick {
Subroutine one_tick: called CC=2 SCAR=6.9
Pod documented
76 204 my $self = _instance(shift);
77 204 ▶ croak 'Mojo::IOLoop already running' if $self->is_running;
Branch: 1 branch
BranchTrueFalseTotal
if $self->is_running 1 203 204
78 203 $self->reactor->one_tick;
79 }
80  
81 5 ▶sub recurring { shift->_timer(recurring => @_) }
Subroutine recurring: called CC=1 SCAR=0.0
Pod documented
82  
83 89 ▶sub remove {
Subroutine remove: called CC=4 SCAR=13.9
Pod documented
84 89 my ($self, $id) = (_instance(shift), @_);
85 89 ▶ my $c = $self->{in}{$id} || $self->{out}{$id};
Condition100%3/3
$self->{'in'}{$id} || $self->{'out'}{$id}
l!l&&r!l&&!r
262439
MC/DC100%2/2
$self->{'in'}{$id} || $self->{'out'}{$id}
$self->{'in'}{$id} $self->{'out'}{$id}
Truth table100%3/3
A || B
A= $self->{'in'}{$id}B= $self->{'out'}{$id}
ABresult
1X1
011
000
86 89 ▶ if ($c && (my $stream = $c->{stream})) { return $stream->close_gracefully }
Branch: 1 branch
BranchTrueFalseTotal
if ($c and my $stream = $c->{"stream"}) 50 39 89
Condition66%2/3
$c and my $stream = $c->{"stream"}
!ll&&!rl&&r
39050
MC/DC50%1/2
$c and my $stream = $c->{"stream"}
$c my $stream = $c->{"stream"}
Truth table66%2/3
A and B
A= $cB= my $stream = $c->{"stream"}
ABresult
0X0
100
111
87 39 $self->_remove($id);
88 }
89  
90 4 ▶sub reset {
Subroutine reset: called CC=3 SCAR=11.0
Pod documented
91 4 ▶ my ($self, $options) = (_instance(shift), shift // {});
Condition100%2/2
shift() // {}
l!l
13
MC/DC100%1/1
shift() // {}
shift()
Truth table100%2/2
A
A= shift()
Aresult
11
00
92  
93 4 $self->emit('reset')->stop;
94 4 ▶ if ($options->{freeze}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options->{'freeze'}) { } 1 3 4
95 1 state @frozen;
96 1 push @frozen, {%$self};
97 1 delete $self->{reactor};
98 }
99 3 else { $self->reactor->reset }
100  
101 4 delete @$self{qw(accepting acceptors events in out stop)};
102 }
103  
104 51 ▶sub server {
Subroutine server: called CC=1 SCAR=0.0
Pod documented
105 51 my ($self, $cb) = (_instance(shift), pop);
106  
107 51 my $server = Mojo::IOLoop::Server->new;
108 51 weaken $self;
109 $server->on(
110 39 ▶ accept => sub {
Subroutine __ANON__: called CC=5 SCAR=16.2
111 39 my $stream = Mojo::IOLoop::Stream->new(pop);
112 39 $self->$cb($stream, $self->_stream($stream, $self->_id, 1));
113  
114 # Enforce connection limit (randomize to improve load balancing)
115 39 ▶ if (my $max = $self->max_accepts) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $max = $self->max_accepts) 1 38 39
116 1 ▶ $self->{accepts} //= $max - int rand $max / 2;
Condition50%1/2
$self->{"accepts"} //= $max - int(rand $max / 2)
l!l
01
MC/DC0%0/1
$self->{"accepts"} //= $max - int(rand $max / 2)
$self->{"accepts"}
Truth table50%1/2
A
A= $self->{"accepts"}
Aresult
11
00
117 1 ▶ $self->stop_gracefully if ($self->{accepts} -= 1) <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"accepts"} -= 1) <= 0 1 0 1
118 }
119  
120 # Stop accepting if connection limit has been reached
121 39 ▶ $self->_not_accepting if $self->_limit;
Branch: 1 branch
BranchTrueFalseTotal
if $self->_limit 3 36 39
122 }
123 51 );
124 51 $server->listen(@_);
125  
126 50 return $self->acceptor($server);
127 }
128  
129 339 ▶sub singleton { state $loop = shift->new }
Subroutine singleton: called CC=1 SCAR=0.0
Pod documented
130  
131 216 ▶sub start {
Subroutine start: called CC=2 SCAR=6.9
Pod documented
132 216 my $self = _instance(shift);
133 216 ▶ croak 'Mojo::IOLoop already running' if $self->is_running;
Branch: 1 branch
BranchTrueFalseTotal
if $self->is_running 3 213 216
134 213 $self->reactor->start;
135 }
136  
137 211 ▶sub stop { _instance(shift)->reactor->stop }
Subroutine stop: called CC=1 SCAR=0.0
Pod documented
138  
139 3 ▶sub stop_gracefully {
Subroutine stop_gracefully: called CC=3 SCAR=11.1
Pod documented
140 3 my $self = _instance(shift)->_not_accepting;
141 3 ▶ ++$self->{stop} and !$self->emit('finish')->_in and $self->stop;
Branch: 1 branch
BranchTrueFalseTotal
++$self->{"stop"} and not $self->emit("finish")->_in and $self->stop 1 2 3
Condition66%2/3
++$self->{"stop"} and not $self->emit("finish")->_in
!ll&&!rl&&r
021
MC/DC50%1/2
++$self->{"stop"} and not $self->emit("finish")->_in
++$self->{"stop"} not $self->emit("finish")->_in
Truth table66%2/3
A and not(B)
A= ++$self->{"stop"}B= not $self->emit("finish")->_in
ABresult
0X0
100
111
142 }
143  
144 1012 ▶sub stream {
Subroutine stream: called CC=4 SCAR=13.9
Pod documented
145 1012 my ($self, $stream) = (_instance(shift), @_);
146 1012 ▶ return $self->_stream($stream => $self->_id) if ref $stream;
Branch: 1 branch
BranchTrueFalseTotal
if ref $stream 1 1011 1012
147 1011 ▶ my $c = $self->{in}{$stream} || $self->{out}{$stream} // {};
Condition100%5/5
($self->{"in"}{$stream} || $self->{"out"}{$stream}) // {}
l!l
10074
$self->{"in"}{$stream} or $self->{"out"}{$stream}
l!l&&r!l&&!r
5104974
MC/DC100%2/2
($self->{"in"}{$stream} || $self->{"out"}{$stream}) // {}
$self->{"in"}{$stream} $self->{"out"}{$stream}
Truth table100%3/3
A or B
A= $self->{"in"}{$stream}B= $self->{"out"}{$stream}
ABresult
1X1
011
000
148 1011 return $c->{stream};
149 }
150  
151 0 ▶sub subprocess {
Subroutine subprocess: not called CC=2 SCAR=17.9
Pod documented
152 0 my $subprocess = Mojo::IOLoop::Subprocess->new(ioloop => _instance(shift));
153 0 ▶ return @_ ? $subprocess->run(@_) : $subprocess;
Branch: 1 branch
BranchTrueFalseTotal
@_ ? : 0 0 0
154 }
155  
156 23 ▶sub timer { shift->_timer(timer => @_) }
Subroutine timer: called CC=1 SCAR=0.0
Pod documented
157  
158 130 ▶sub _id {
Subroutine _id: called CC=4 SCAR=15.9
159 130 my $self = shift;
160 130 my $id;
161 130 ▶ do { $id = md5_sum 'c' . steady_time . rand } while $self->{in}{$id} || $self->{out}{$id} || $self->{acceptors}{$id};
Branch: 1 branch
BranchTrueFalseTotal
$self->{"in"}{$id} || $self->{"out"}{$id} || $self->{"acceptors"}{$id} and do { do { $id = md5_sum('c' . &steady_time() . (rand)) } } 0 130 130
Condition33%2/6
$self->{"in"}{$id} or $self->{"out"}{$id} or $self->{"acceptors"}{$id}
l!l&&r!l&&!r
00130
$self->{"in"}{$id} or $self->{"out"}{$id}
l!l&&r!l&&!r
00130
MC/DC0%0/3
$self->{"in"}{$id} or $self->{"out"}{$id} or $self->{"acceptors"}{$id}
$self->{"in"}{$id} $self->{"out"}{$id} $self->{"acceptors"}{$id}
Truth table25%1/4
A or B or C
A= $self->{"in"}{$id}B= $self->{"out"}{$id}C= $self->{"acceptors"}{$id}
ABCresult
1XX1
01X1
0011
0000
162 130 return $id;
163 }
164  
165 133 ▶sub _in { scalar keys %{shift->{in} // {}} }
Subroutine _in: called CC=2 SCAR=6.9
Condition100%2/2
+(shift())->{"in"} // {}
l!l
1321
MC/DC100%1/1
+(shift())->{"in"} // {}
+(shift())->{"in"}
Truth table100%2/2
A
A= +(shift())->{"in"}
Aresult
11
00
166  
167 3373 ▶sub _instance { ref $_[0] ? $_[0] : $_[0]->singleton }
Subroutine _instance: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] ? : 3245 128 3373
168  
169 129 ▶sub _limit { $_[0]{stop} ? 1 : $_[0]->_in >= $_[0]->max_connections }
Subroutine _limit: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
$_[0]{'stop'} ? : 3 126 129
170  
171 142 ▶sub _maybe_accepting {
Subroutine _maybe_accepting: called CC=5 SCAR=16.1
172 142 my $self = shift;
173 142 ▶ return if $self->{accepting} || $self->_limit;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"accepting"} or $self->_limit 54 88 142
Condition100%3/3
$self->{"accepting"} or $self->_limit
l!l&&r!l&&!r
52288
MC/DC100%2/2
$self->{"accepting"} or $self->_limit
$self->{"accepting"} $self->_limit
Truth table100%3/3
A or B
A= $self->{"accepting"}B= $self->_limit
ABresult
1X1
011
000
174 88 ▶ $_->start for values %{$self->{acceptors} // {}};
Condition50%1/2
$self->{"acceptors"} // {}
l!l
880
MC/DC0%0/1
$self->{"acceptors"} // {}
$self->{"acceptors"}
Truth table50%1/2
A
A= $self->{"acceptors"}
Aresult
11
00
175 88 $self->{accepting} = 1;
176 }
177  
178 93 ▶sub _not_accepting {
Subroutine _not_accepting: called CC=4 SCAR=13.9
179 93 my $self = shift;
180 93 ▶ return $self unless delete $self->{accepting};
Branch: 1 branch
BranchTrueFalseTotal
unless delete $self->{"accepting"} 22 71 93
181 71 ▶ $_->stop for values %{$self->{acceptors} // {}};
Condition50%1/2
$self->{"acceptors"} // {}
l!l
710
MC/DC0%0/1
$self->{"acceptors"} // {}
$self->{"acceptors"}
Truth table50%1/2
A
A= $self->{"acceptors"}
Aresult
11
00
182 71 return $self;
183 }
184  
185 0 ▶sub _out { scalar keys %{shift->{out} // {}} }
Subroutine _out: not called CC=2 SCAR=17.9
Condition0%0/2
+(shift())->{"out"} // {}
l!l
00
MC/DC0%0/1
+(shift())->{"out"} // {}
+(shift())->{"out"}
Truth table0%0/2
A
A= +(shift())->{"out"}
Aresult
11
00
186  
187 98 ▶sub _remove {
Subroutine _remove: called CC=8 SCAR=20.8
188 98 my ($self, $id) = @_;
189  
190 # Timer
191 98 ▶ return undef unless my $reactor = $self->reactor;
Branch: 1 branch
BranchTrueFalseTotal
unless my $reactor = $self->reactor 0 98 98
192 98 ▶ return undef if $reactor->remove($id);
Branch: 1 branch
BranchTrueFalseTotal
if $reactor->remove($id) 3 95 98
193  
194 # Acceptor
195 95 ▶ return $self->_not_accepting->_maybe_accepting if delete $self->{acceptors}{$id};
Branch: 1 branch
BranchTrueFalseTotal
if delete $self->{"acceptors"}{$id} 36 59 95
196  
197 # Connection
198 59 ▶ return undef unless delete $self->{in}{$id} || delete $self->{out}{$id};
Branch: 1 branch
BranchTrueFalseTotal
unless delete $self->{"in"}{$id} or delete $self->{"out"}{$id} 2 57 59
Condition100%3/3
delete $self->{"in"}{$id} or delete $self->{"out"}{$id}
l!l&&r!l&&!r
30272
MC/DC100%2/2
delete $self->{"in"}{$id} or delete $self->{"out"}{$id}
delete $self->{"in"}{$id} delete $self->{"out"}{$id}
Truth table100%3/3
A or B
A= delete $self->{"in"}{$id}B= delete $self->{"out"}{$id}
ABresult
1X1
011
000
199 57 ▶ return $self->stop if $self->{stop} && !$self->_in;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"stop"} and not $self->_in 2 55 57
Condition100%3/3
$self->{"stop"} and not $self->_in
!ll&&!rl&&r
5322
MC/DC100%2/2
$self->{"stop"} and not $self->_in
$self->{"stop"} not $self->_in
Truth table100%3/3
A and not(B)
A= $self->{"stop"}B= not $self->_in
ABresult
0X0
100
111
200 55 $self->_maybe_accepting;
201 55 warn "-- $id <<< $$ (@{[$self->_in]}:@{[$self->_out]})\n" if DEBUG;
202 }
203  
204 79 ▶sub _stream {
Subroutine _stream: called CC=2 SCAR=6.9
205 79 my ($self, $stream, $id, $server) = @_;
206  
207 # Connect stream with reactor
208 79 ▶ $self->{$server ? 'in' : 'out'}{$id}{stream} = $stream->reactor($self->reactor);
Branch: 1 branch
BranchTrueFalseTotal
$server ? : 39 40 79
209 79 warn "-- $id >>> $$ (@{[$self->_in]}:@{[$self->_out]})\n" if DEBUG;
210 79 weaken $self;
211 79 ▶ $stream->on(close => sub { $self && $self->_remove($id) });
Subroutine __ANON__: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
$self and $self->_remove($id) 59 0 59
212 79 $stream->start;
213  
214 79 return $id;
215 }
216  
217 28 ▶sub _timer {
Subroutine _timer: called CC=1 SCAR=0.0
218 28 my ($self, $method, $after, $cb) = (_instance(shift), @_);
219 28 weaken $self;
220 28 ▶ return $self->reactor->$method($after => sub { $self->$cb });
Subroutine __ANON__: called CC=1 SCAR=0.0
221 }
222  
223 33 1;
224  
225 =encoding utf8
226  
227 =head1 NAME
228  
229 Mojo::IOLoop - Minimalistic event loop
230  
231 =head1 SYNOPSIS
232  
233 use Mojo::IOLoop;
234  
235 # Listen on port 3000
236 Mojo::IOLoop->server({port => 3000} => sub ($loop, $stream, $id) {
237 $stream->on(read => sub ($stream, $bytes) {
238 # Process input chunk
239 say $bytes;
240  
241 # Write response
242 $stream->write('HTTP/1.1 200 OK');
243 });
244 });
245  
246 # Connect to port 3000
247 my $id = Mojo::IOLoop->client({port => 3000} => sub ($loop, $err, $stream) {
248 $stream->on(read => sub ($stream, $bytes) {
249 # Process input
250 say "Input: $bytes";
251 });
252  
253 # Write request
254 $stream->write("GET / HTTP/1.1\x0d\x0a\x0d\x0a");
255 });
256  
257 # Add a timer
258 Mojo::IOLoop->timer(5 => sub ($loop) { $loop->remove($id) });
259  
260 # Start event loop if necessary
261 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
262  
263 =head1 DESCRIPTION
264  
265 L<Mojo::IOLoop> is a very minimalistic event loop based on L<Mojo::Reactor>, it has been reduced to the absolute
266 minimal feature set required to build solid and scalable non-blocking clients and servers.
267  
268 Depending on operating system, the default per-process and system-wide file descriptor limits are often very low and
269 need to be tuned for better scalability. The C<LIBEV_FLAGS> environment variable should also be used to select the best
270 possible L<EV> backend, which usually defaults to the not very scalable C<select>.
271  
272 LIBEV_FLAGS=1 # select
273 LIBEV_FLAGS=2 # poll
274 LIBEV_FLAGS=4 # epoll (Linux)
275 LIBEV_FLAGS=8 # kqueue (*BSD, OS X)
276 LIBEV_FLAGS=64 # Linux AIO
277  
278 The event loop will be resilient to time jumps if a monotonic clock is available through L<Time::HiRes>. A TLS
279 certificate and key are also built right in, to make writing test servers as easy as possible. Also note that for
280 convenience the C<PIPE> signal will be set to C<IGNORE> when L<Mojo::IOLoop> is loaded.
281  
282 For better scalability (epoll, kqueue) and to provide non-blocking name resolution, SOCKS5 as well as TLS support, the
283 optional modules L<EV> (4.32+), L<Net::DNS::Native> (0.15+), L<IO::Socket::Socks> (0.64+) and L<IO::Socket::SSL>
284 (2.009+) will be used automatically if possible. Individual features can also be disabled with the C<MOJO_NO_NNR>,
285 C<MOJO_NO_SOCKS> and C<MOJO_NO_TLS> environment variables.
286  
287 See L<Mojolicious::Guides::Cookbook/"REAL-TIME WEB"> for more.
288  
289 =head1 EVENTS
290  
291 L<Mojo::IOLoop> inherits all events from L<Mojo::EventEmitter> and can emit the following new ones.
292  
293 =head2 finish
294  
295 $loop->on(finish => sub ($loop) {...});
296  
297 Emitted when the event loop wants to shut down gracefully and is just waiting for all existing connections to be
298 closed.
299  
300 =head2 reset
301  
302 $loop->on(reset => sub ($loop) {...});
303  
304 Emitted when the event loop is reset, this usually happens after the process is forked to clean up resources that
305 cannot be shared.
306  
307 =head1 ATTRIBUTES
308  
309 L<Mojo::IOLoop> implements the following attributes.
310  
311 =head2 max_accepts
312  
313 my $max = $loop->max_accepts;
314 $loop = $loop->max_accepts(1000);
315  
316 The maximum number of connections this event loop is allowed to accept, before shutting down gracefully without
317 interrupting existing connections, defaults to C<0>. Setting the value to C<0> will allow this event loop to accept new
318 connections indefinitely. Note that up to half of this value can be subtracted randomly to improve load balancing
319 between multiple server processes, and to make sure that not all of them restart at the same time.
320  
321 =head2 max_connections
322  
323 my $max = $loop->max_connections;
324 $loop = $loop->max_connections(100);
325  
326 The maximum number of accepted connections this event loop is allowed to handle concurrently, before stopping to accept
327 new incoming connections, defaults to C<1000>.
328  
329 =head2 reactor
330  
331 my $reactor = $loop->reactor;
332 $loop = $loop->reactor(Mojo::Reactor->new);
333  
334 Low-level event reactor, usually a L<Mojo::Reactor::Poll> or L<Mojo::Reactor::EV> object with a default subscriber to
335 the event L<Mojo::Reactor/"error">.
336  
337 # Watch if handle becomes readable or writable
338 Mojo::IOLoop->singleton->reactor->io($handle => sub ($reactor, $writable) {
339 say $writable ? 'Handle is writable' : 'Handle is readable';
340 });
341  
342 # Change to watching only if handle becomes writable
343 Mojo::IOLoop->singleton->reactor->watch($handle, 0, 1);
344  
345 # Remove handle again
346 Mojo::IOLoop->singleton->reactor->remove($handle);
347  
348 =head1 METHODS
349  
350 L<Mojo::IOLoop> inherits all methods from L<Mojo::EventEmitter> and implements the following new ones.
351  
352 =head2 acceptor
353  
354 my $server = Mojo::IOLoop->acceptor($id);
355 my $server = $loop->acceptor($id);
356 my $id = $loop->acceptor(Mojo::IOLoop::Server->new);
357  
358 Get L<Mojo::IOLoop::Server> object for id or turn object into an acceptor.
359  
360 =head2 client
361  
362 my $id = Mojo::IOLoop->client(address => '127.0.0.1', port => 3000, sub {...});
363 my $id = $loop->client(address => '127.0.0.1', port => 3000, sub {...});
364 my $id = $loop->client({address => '127.0.0.1', port => 3000} => sub {...});
365  
366 Open a TCP/IP or UNIX domain socket connection with L<Mojo::IOLoop::Client> and create a stream object (usually
367 L<Mojo::IOLoop::Stream>), takes the same arguments as L<Mojo::IOLoop::Client/"connect">.
368  
369 =head2 is_running
370  
371 my $bool = Mojo::IOLoop->is_running;
372 my $bool = $loop->is_running;
373  
374 Check if event loop is running.
375  
376 =head2 next_tick
377  
378 my $undef = Mojo::IOLoop->next_tick(sub ($loop) {...});
379 my $undef = $loop->next_tick(sub ($loop) {...});
380  
381 Execute callback as soon as possible, but not before returning or other callbacks that have been registered with this
382 method, always returns C<undef>.
383  
384 # Perform operation on next reactor tick
385 Mojo::IOLoop->next_tick(sub ($loop) {...});
386  
387 =head2 one_tick
388  
389 Mojo::IOLoop->one_tick;
390 $loop->one_tick;
391  
392 Run event loop until an event occurs.
393  
394 # Don't block longer than 0.5 seconds
395 my $id = Mojo::IOLoop->timer(0.5 => sub ($loop) {});
396 Mojo::IOLoop->one_tick;
397 Mojo::IOLoop->remove($id);
398  
399 =head2 recurring
400  
401 my $id = Mojo::IOLoop->recurring(3 => sub ($loop) {...});
402 my $id = $loop->recurring(0 => sub ($loop) {...});
403 my $id = $loop->recurring(0.25 => sub ($loop) {...});
404  
405 Create a new recurring timer, invoking the callback repeatedly after a given amount of time in seconds.
406  
407 # Perform operation every 5 seconds
408 Mojo::IOLoop->recurring(5 => sub ($loop) {...});
409  
410 =head2 remove
411  
412 Mojo::IOLoop->remove($id);
413 $loop->remove($id);
414  
415 Remove anything with an id, connections will be dropped gracefully by allowing them to finish writing all data in their
416 write buffers.
417  
418 =head2 reset
419  
420 Mojo::IOLoop->reset;
421 $loop->reset;
422 $loop->reset({freeze => 1});
423  
424 Remove everything and stop the event loop.
425  
426 These options are currently available:
427  
428 =over 2
429  
430 =item freeze
431  
432 freeze => 1
433  
434 Freeze the current state of the event loop in time before resetting it. This will prevent active connections from
435 getting closed immediately, which can help with many unintended side effects when processes are forked.
436  
437 =back
438  
439 =head2 server
440  
441 my $id = Mojo::IOLoop->server(port => 3000, sub {...});
442 my $id = $loop->server(port => 3000, sub {...});
443 my $id = $loop->server({port => 3000} => sub {...});
444  
445 Accept TCP/IP and UNIX domain socket connections with L<Mojo::IOLoop::Server> and create stream objects (usually
446 L<Mojo::IOLoop::Stream>, takes the same arguments as L<Mojo::IOLoop::Server/"listen">.
447  
448 # Listen on random port
449 my $id = Mojo::IOLoop->server({address => '127.0.0.1'} => sub ($loop, $stream, $id) {...});
450 my $port = Mojo::IOLoop->acceptor($id)->port;
451  
452 =head2 singleton
453  
454 my $loop = Mojo::IOLoop->singleton;
455  
456 The global L<Mojo::IOLoop> singleton, used to access a single shared event loop object from everywhere inside the
457 process.
458  
459 # Many methods also allow you to take shortcuts
460 Mojo::IOLoop->timer(2 => sub { Mojo::IOLoop->stop });
461 Mojo::IOLoop->start;
462  
463 # Restart active timer
464 my $id = Mojo::IOLoop->timer(3 => sub { say 'Timeout!' });
465 Mojo::IOLoop->singleton->reactor->again($id);
466  
467 # Turn file descriptor into handle and watch if it becomes readable
468 my $handle = IO::Handle->new_from_fd($fd, 'r');
469 Mojo::IOLoop->singleton->reactor->io($handle => sub ($reactor, $writable) {
470 say $writable ? 'Handle is writable' : 'Handle is readable';
471 })->watch($handle, 1, 0);
472  
473 =head2 start
474  
475 Mojo::IOLoop->start;
476 $loop->start;
477  
478 Start the event loop, this will block until L</"stop"> is called. Note that some reactors stop automatically if there
479 are no events being watched anymore.
480  
481 # Start event loop only if it is not running already
482 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
483  
484 =head2 stop
485  
486 Mojo::IOLoop->stop;
487 $loop->stop;
488  
489 Stop the event loop, this will not interrupt any existing connections and the event loop can be restarted by running
490 L</"start"> again.
491  
492 =head2 stop_gracefully
493  
494 Mojo::IOLoop->stop_gracefully;
495 $loop->stop_gracefully;
496  
497 Stop accepting new connections and wait for already accepted connections to be closed, before stopping the event loop.
498  
499 =head2 stream
500  
501 my $stream = Mojo::IOLoop->stream($id);
502 my $stream = $loop->stream($id);
503 my $id = $loop->stream(Mojo::IOLoop::Stream->new);
504  
505 Get L<Mojo::IOLoop::Stream> object for id or turn object into a connection.
506  
507 # Increase inactivity timeout for connection to 300 seconds
508 Mojo::IOLoop->stream($id)->timeout(300);
509  
510 =head2 subprocess
511  
512 my $subprocess = Mojo::IOLoop->subprocess;
513 my $subprocess = $loop->subprocess;
514 my $subprocess = $loop->subprocess(sub ($subprocess) {...}, sub ($subprocess, $err, @results) {...});
515  
516 Build L<Mojo::IOLoop::Subprocess> object to perform computationally expensive operations in subprocesses, without
517 blocking the event loop. Callbacks will be passed along to L<Mojo::IOLoop::Subprocess/"run">.
518  
519 # Operation that would block the event loop for 5 seconds
520 Mojo::IOLoop->subprocess->run_p(sub {
521 sleep 5;
522 return '♥', 'Mojolicious';
523 })->then(sub (@results) {
524 say "I $results[0] $results[1]!";
525 })->catch(sub ($err) {
526 say "Subprocess error: $err";
527 });
528  
529 =head2 timer
530  
531 my $id = Mojo::IOLoop->timer(3 => sub ($loop) {...});
532 my $id = $loop->timer(0 => sub ($loop) {...});
533 my $id = $loop->timer(0.25 => sub ($loop) {...});
534  
535 Create a new timer, invoking the callback after a given amount of time in seconds.
536  
537 # Perform operation in 5 seconds
538 Mojo::IOLoop->timer(5 => sub ($loop) {...});
539  
540 =head1 DEBUGGING
541  
542 You can set the C<MOJO_IOLOOP_DEBUG> environment variable to get some advanced diagnostics information printed to
543 C<STDERR>.
544  
545 MOJO_IOLOOP_DEBUG=1
546  
547 =head1 SEE ALSO
548  
549 L<Mojolicious>, L<Mojolicious::Guides>, L<https://mojolicious.org>.
550  
551 =cut
« Mojolicious/Plugin/EPRenderer.pm ↑ Summary Mojolicious/Command/prefork.pm »