1Mojo::IOLoop(3) User Contributed Perl Documentation Mojo::IOLoop(3)
2
3
4
6 Mojo::IOLoop - Minimalistic event loop
7
9 use Mojo::IOLoop;
10
11 # Listen on port 3000
12 Mojo::IOLoop->server({port => 3000} => sub {
13 my ($loop, $stream) = @_;
14
15 $stream->on(read => sub {
16 my ($stream, $bytes) = @_;
17
18 # Process input chunk
19 say $bytes;
20
21 # Write response
22 $stream->write('HTTP/1.1 200 OK');
23 });
24 });
25
26 # Connect to port 3000
27 my $id = Mojo::IOLoop->client({port => 3000} => sub {
28 my ($loop, $err, $stream) = @_;
29
30 $stream->on(read => sub {
31 my ($stream, $bytes) = @_;
32
33 # Process input
34 say "Input: $bytes";
35 });
36
37 # Write request
38 $stream->write("GET / HTTP/1.1\x0d\x0a\x0d\x0a");
39 });
40
41 # Add a timer
42 Mojo::IOLoop->timer(5 => sub {
43 my $loop = shift;
44 $loop->remove($id);
45 });
46
47 # Start event loop if necessary
48 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
49
51 Mojo::IOLoop is a very minimalistic event loop based on Mojo::Reactor,
52 it has been reduced to the absolute minimal feature set required to
53 build solid and scalable non-blocking clients and servers.
54
55 Depending on operating system, the default per-process and system-wide
56 file descriptor limits are often very low and need to be tuned for
57 better scalability. The "LIBEV_FLAGS" environment variable should also
58 be used to select the best possible EV backend, which usually defaults
59 to the not very scalable "select".
60
61 LIBEV_FLAGS=1 # select
62 LIBEV_FLAGS=2 # poll
63 LIBEV_FLAGS=4 # epoll (Linux)
64 LIBEV_FLAGS=8 # kqueue (*BSD, OS X)
65
66 The event loop will be resilient to time jumps if a monotonic clock is
67 available through Time::HiRes. A TLS certificate and key are also built
68 right in, to make writing test servers as easy as possible. Also note
69 that for convenience the "PIPE" signal will be set to "IGNORE" when
70 Mojo::IOLoop is loaded.
71
72 For better scalability (epoll, kqueue) and to provide non-blocking name
73 resolution, SOCKS5 as well as TLS support, the optional modules EV
74 (4.0+), Net::DNS::Native (0.15+), IO::Socket::Socks (0.64+) and
75 IO::Socket::SSL (2.009+) will be used automatically if possible.
76 Individual features can also be disabled with the "MOJO_NO_NNR",
77 "MOJO_NO_SOCKS" and "MOJO_NO_TLS" environment variables.
78
79 See "REAL-TIME WEB" in Mojolicious::Guides::Cookbook for more.
80
82 Mojo::IOLoop inherits all events from Mojo::EventEmitter and can emit
83 the following new ones.
84
85 finish
86 $loop->on(finish => sub {
87 my $loop = shift;
88 ...
89 });
90
91 Emitted when the event loop wants to shut down gracefully and is just
92 waiting for all existing connections to be closed.
93
95 Mojo::IOLoop implements the following attributes.
96
97 max_accepts
98 my $max = $loop->max_accepts;
99 $loop = $loop->max_accepts(1000);
100
101 The maximum number of connections this event loop is allowed to accept,
102 before shutting down gracefully without interrupting existing
103 connections, defaults to 0. Setting the value to 0 will allow this
104 event loop to accept new connections indefinitely. Note that up to half
105 of this value can be subtracted randomly to improve load balancing
106 between multiple server processes, and to make sure that not all of
107 them restart at the same time.
108
109 max_connections
110 my $max = $loop->max_connections;
111 $loop = $loop->max_connections(100);
112
113 The maximum number of accepted connections this event loop is allowed
114 to handle concurrently, before stopping to accept new incoming
115 connections, defaults to 1000.
116
117 reactor
118 my $reactor = $loop->reactor;
119 $loop = $loop->reactor(Mojo::Reactor->new);
120
121 Low-level event reactor, usually a Mojo::Reactor::Poll or
122 Mojo::Reactor::EV object with a default subscriber to the event "error"
123 in Mojo::Reactor.
124
125 # Watch if handle becomes readable or writable
126 Mojo::IOLoop->singleton->reactor->io($handle => sub {
127 my ($reactor, $writable) = @_;
128 say $writable ? 'Handle is writable' : 'Handle is readable';
129 });
130
131 # Change to watching only if handle becomes writable
132 Mojo::IOLoop->singleton->reactor->watch($handle, 0, 1);
133
134 # Remove handle again
135 Mojo::IOLoop->singleton->reactor->remove($handle);
136
138 Mojo::IOLoop inherits all methods from Mojo::EventEmitter and
139 implements the following new ones.
140
141 acceptor
142 my $server = Mojo::IOLoop->acceptor($id);
143 my $server = $loop->acceptor($id);
144 my $id = $loop->acceptor(Mojo::IOLoop::Server->new);
145
146 Get Mojo::IOLoop::Server object for id or turn object into an acceptor.
147
148 client
149 my $id
150 = Mojo::IOLoop->client(address => '127.0.0.1', port => 3000, sub {...});
151 my $id = $loop->client(address => '127.0.0.1', port => 3000, sub {...});
152 my $id = $loop->client({address => '127.0.0.1', port => 3000} => sub {...});
153
154 Open a TCP/IP or UNIX domain socket connection with
155 Mojo::IOLoop::Client and create a stream object (usually
156 Mojo::IOLoop::Stream), takes the same arguments as "connect" in
157 Mojo::IOLoop::Client.
158
159 delay
160 my $delay = Mojo::IOLoop->delay;
161 my $delay = $loop->delay;
162 my $delay = $loop->delay(sub {...});
163 my $delay = $loop->delay(sub {...}, sub {...});
164
165 Build Mojo::IOLoop::Delay object to use as a promise and/or for flow-
166 control. Callbacks will be passed along to "steps" in
167 Mojo::IOLoop::Delay.
168
169 # Wrap continuation-passing style APIs with promises
170 my $ua = Mojo::UserAgent->new;
171 sub get {
172 my $promise = Mojo::IOLoop->delay;
173 $ua->get(@_ => sub {
174 my ($ua, $tx) = @_;
175 my $err = $tx->error;
176 $promise->resolve($tx) if !$err || $err->{code};
177 $promise->reject($err->{message});
178 });
179 return $promise;
180 }
181 my $mojo = get('https://mojolicious.org');
182 my $cpan = get('https://metacpan.org');
183 Mojo::Promise->race($mojo, $cpan)->then(sub { say shift->req->url })->wait;
184
185 # Synchronize multiple non-blocking operations
186 my $delay = Mojo::IOLoop->delay(sub { say 'BOOM!' });
187 for my $i (1 .. 10) {
188 my $end = $delay->begin;
189 Mojo::IOLoop->timer($i => sub {
190 say 10 - $i;
191 $end->();
192 });
193 }
194 $delay->wait;
195
196 # Sequentialize multiple non-blocking operations
197 Mojo::IOLoop->delay(
198
199 # First step (simple timer)
200 sub {
201 my $delay = shift;
202 Mojo::IOLoop->timer(2 => $delay->begin);
203 say 'Second step in 2 seconds.';
204 },
205
206 # Second step (concurrent timers)
207 sub {
208 my $delay = shift;
209 Mojo::IOLoop->timer(1 => $delay->begin);
210 Mojo::IOLoop->timer(3 => $delay->begin);
211 say 'Third step in 3 seconds.';
212 },
213
214 # Third step (the end)
215 sub { say 'And done after 5 seconds total.' }
216 )->wait;
217
218 is_running
219 my $bool = Mojo::IOLoop->is_running;
220 my $bool = $loop->is_running;
221
222 Check if event loop is running.
223
224 next_tick
225 my $undef = Mojo::IOLoop->next_tick(sub {...});
226 my $undef = $loop->next_tick(sub {...});
227
228 Execute callback as soon as possible, but not before returning or other
229 callbacks that have been registered with this method, always returns
230 "undef".
231
232 # Perform operation on next reactor tick
233 Mojo::IOLoop->next_tick(sub {
234 my $loop = shift;
235 ...
236 });
237
238 one_tick
239 Mojo::IOLoop->one_tick;
240 $loop->one_tick;
241
242 Run event loop until an event occurs.
243
244 # Don't block longer than 0.5 seconds
245 my $id = Mojo::IOLoop->timer(0.5 => sub {});
246 Mojo::IOLoop->one_tick;
247 Mojo::IOLoop->remove($id);
248
249 recurring
250 my $id = Mojo::IOLoop->recurring(3 => sub {...});
251 my $id = $loop->recurring(0 => sub {...});
252 my $id = $loop->recurring(0.25 => sub {...});
253
254 Create a new recurring timer, invoking the callback repeatedly after a
255 given amount of time in seconds.
256
257 # Perform operation every 5 seconds
258 Mojo::IOLoop->recurring(5 => sub {
259 my $loop = shift;
260 ...
261 });
262
263 remove
264 Mojo::IOLoop->remove($id);
265 $loop->remove($id);
266
267 Remove anything with an id, connections will be dropped gracefully by
268 allowing them to finish writing all data in their write buffers.
269
270 reset
271 Mojo::IOLoop->reset;
272 $loop->reset;
273
274 Remove everything and stop the event loop.
275
276 server
277 my $id = Mojo::IOLoop->server(port => 3000, sub {...});
278 my $id = $loop->server(port => 3000, sub {...});
279 my $id = $loop->server({port => 3000} => sub {...});
280
281 Accept TCP/IP and UNIX domain socket connections with
282 Mojo::IOLoop::Server and create stream objects (usually
283 Mojo::IOLoop::Stream, takes the same arguments as "listen" in
284 Mojo::IOLoop::Server.
285
286 # Listen on random port
287 my $id = Mojo::IOLoop->server({address => '127.0.0.1'} => sub {
288 my ($loop, $stream, $id) = @_;
289 ...
290 });
291 my $port = Mojo::IOLoop->acceptor($id)->port;
292
293 singleton
294 my $loop = Mojo::IOLoop->singleton;
295
296 The global Mojo::IOLoop singleton, used to access a single shared event
297 loop object from everywhere inside the process.
298
299 # Many methods also allow you to take shortcuts
300 Mojo::IOLoop->timer(2 => sub { Mojo::IOLoop->stop });
301 Mojo::IOLoop->start;
302
303 # Restart active timer
304 my $id = Mojo::IOLoop->timer(3 => sub { say 'Timeout!' });
305 Mojo::IOLoop->singleton->reactor->again($id);
306
307 # Turn file descriptor into handle and watch if it becomes readable
308 my $handle = IO::Handle->new_from_fd($fd, 'r');
309 Mojo::IOLoop->singleton->reactor->io($handle => sub {
310 my ($reactor, $writable) = @_;
311 say $writable ? 'Handle is writable' : 'Handle is readable';
312 })->watch($handle, 1, 0);
313
314 start
315 Mojo::IOLoop->start;
316 $loop->start;
317
318 Start the event loop, this will block until "stop" is called. Note that
319 some reactors stop automatically if there are no events being watched
320 anymore.
321
322 # Start event loop only if it is not running already
323 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
324
325 stop
326 Mojo::IOLoop->stop;
327 $loop->stop;
328
329 Stop the event loop, this will not interrupt any existing connections
330 and the event loop can be restarted by running "start" again.
331
332 stop_gracefully
333 Mojo::IOLoop->stop_gracefully;
334 $loop->stop_gracefully;
335
336 Stop accepting new connections and wait for already accepted
337 connections to be closed, before stopping the event loop.
338
339 stream
340 my $stream = Mojo::IOLoop->stream($id);
341 my $stream = $loop->stream($id);
342 my $id = $loop->stream(Mojo::IOLoop::Stream->new);
343
344 Get Mojo::IOLoop::Stream object for id or turn object into a
345 connection.
346
347 # Increase inactivity timeout for connection to 300 seconds
348 Mojo::IOLoop->stream($id)->timeout(300);
349
350 subprocess
351 my $subprocess = Mojo::IOLoop->subprocess(sub {...}, sub {...});
352 my $subprocess = $loop->subprocess;
353 my $subprocess = $loop->subprocess(sub {...}, sub {...});
354
355 Build Mojo::IOLoop::Subprocess object to perform computationally
356 expensive operations in subprocesses, without blocking the event loop.
357 Callbacks will be passed along to "run" in Mojo::IOLoop::Subprocess.
358
359 # Operation that would block the event loop for 5 seconds
360 Mojo::IOLoop->subprocess(
361 sub {
362 my $subprocess = shift;
363 sleep 5;
364 return '♥', 'Mojolicious';
365 },
366 sub {
367 my ($subprocess, $err, @results) = @_;
368 say "Subprocess error: $err" and return if $err;
369 say "I $results[0] $results[1]!";
370 }
371 );
372
373 timer
374 my $id = Mojo::IOLoop->timer(3 => sub {...});
375 my $id = $loop->timer(0 => sub {...});
376 my $id = $loop->timer(0.25 => sub {...});
377
378 Create a new timer, invoking the callback after a given amount of time
379 in seconds.
380
381 # Perform operation in 5 seconds
382 Mojo::IOLoop->timer(5 => sub {
383 my $loop = shift;
384 ...
385 });
386
388 You can set the "MOJO_IOLOOP_DEBUG" environment variable to get some
389 advanced diagnostics information printed to "STDERR".
390
391 MOJO_IOLOOP_DEBUG=1
392
394 Mojolicious, Mojolicious::Guides, <https://mojolicious.org>.
395
396
397
398perl v5.28.0 2018-10-15 Mojo::IOLoop(3)