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