Scheduling and events
CRON(), ON(), ONCE(), OFF(), EMIT(), the built-in events, setTimeout2(), CLEANUP() and PAUSESERVER().
On this page
Global functions for scheduled and event-driven code: CRON() runs functions on a cron line, ON(), ONCE(), OFF() and EMIT() work with global events, and the framework emits its own events such as ready, service, exit and error. setTimeout2() and clearTimeout2() give named debounced timers, CLEANUP() waits for a stream and PAUSESERVER() holds incoming traffic.
The guide Scheduling and events explains how they work together.
API
method
CRON(line, fn)
Runs a function when the date matches a cron line.
CRON(line, fn)| Parameter | Type | Description |
|---|---|---|
line |
String |
The cron line, e.g. 0 3 * * *. |
fn |
Function |
function(date), called when the line matches. |
Returns Object The cron, with check(date), exec(date) and remove().
The line has five fields: minute, hour, day of the month, month and day of the week (0–6, or su, mo, tu, we, th, fr, sa). Each field is *, a number, a list (1,15), a range (8-17) or a step: */15 matches every 15th value from the first value of the field (minutes 0, 15, 30, 45; days of the month 1, 16, 31) and 5/20 every 20th value from 5 (5, 25, 45). The crons are checked once a minute by the service timer and fn gets the current date (NOW). Hours and days follow the time zone of the process ($timezone, default utc).
CRON('0 3 * * *', function(date) {
NOSQL('logs').remove().where('date', '<', date.add('-30 days'));
});
CRON('30 8 * * mo-fr', function() {
MAIL(CONF.mail_report, 'Daily report', 'mail/report', {});
});
CRON('*/15 * * * *', function() {
// at minutes 0, 15, 30 and 45
});
method
cron.remove()
Stops a cron.
cron.remove()Removes the cron returned by CRON() from F.crons, so it does not run any more.
var cron = CRON('0 12 * * *', function() {
sendreport();
cron.remove();
});
property
F.crons
The registered crons.
F.cronsReturns Array
An array of the objects returned by CRON(), in the order they were registered. Each has check(date) (returns true when the line matches), exec(date) (your function) and remove().
console.log(F.crons.length + ' crons');
method
ON(name, fn)
Adds a listener of a global event.
ON(name, fn)| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the event, or several names joined with +. |
fn |
Function |
The listener; it gets the arguments of EMIT(). |
Join several names with + to add the same listener to each of them. A listener of ready added after the application is loaded is called at once. Inside the listener this is F. F.on() is the same method.
ON('order.created', function(order) {
console.log('New order', order.id);
});
ON('ready + service', function() {
refreshcache();
});
method
ONCE(name, fn)
Adds a listener that runs only once.
ONCE(name, fn)| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the event. |
fn |
Function |
The listener. |
The listener is removed after the first emission of the event. Names joined with + work as in ON(), and a ready listener added after the load runs at once. F.once() is the same method.
ONCE('service', function() {
console.log('The first minute has passed');
});
method
OFF(name, [fn])
Removes a listener of a global event.
OFF(name, [fn])| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the event. |
fn? |
Function |
The listener to remove. |
With fn, removes that listener; it must be the same function that was passed to ON(). Without fn, removes all listeners of the event, including listeners of the framework. F.off() is the same method.
function onservice(counter) {
if (counter === 60)
OFF('service', onservice);
}
ON('service', onservice);
method
EMIT(name, [a], [b], [c], [d], [e], [f], [g])
Emits a global event.
EMIT(name, [a], [b], [c], [d], [e], [f], [g])| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the event. |
a...g? |
Object |
Up to seven arguments for the listeners. |
Calls all listeners of name in the order they were added, synchronously, with up to seven arguments. Listeners added with ONCE() are removed afterwards. F.emit() is the same method.
EMIT('order.created', { id: 123, email: 'buyer@example.com' });
method
setTimeout2(id, callback, timeout, [limit])
A named timer that restarts on every call (a debounce).
setTimeout2(id, callback, timeout, [limit])| Parameter | Type | Description |
|---|---|---|
id |
String |
The name of the timer. |
callback |
Function |
The function to run. |
timeout |
Number |
The delay in milliseconds. |
limit? |
Number |
How many times the timer can be postponed before a call runs the callback at once. 0 means no limit. Default: 0 |
If a timer with the same id is waiting, it is canceled and a new timer starts with the new callback. The callback runs only after timeout milliseconds without a new call with that id.
With limit, the timer can be postponed only limit times: the next call cancels the timer and runs its callback at once, and the counting starts again. Use it when the callback must run from time to time even while the calls do not stop.
function changed(doc) {
setTimeout2('save' + doc.id, function() {
NOSQL('docs').modify(doc).where('id', doc.id);
}, 2000);
}
function onkey(text) {
// searches after a pause of 300 ms, or at once when the timer has been postponed 10 times
setTimeout2('search', function() {
search(text);
}, 300, 10);
}
method
clearTimeout2(id)
Cancels a named timer of setTimeout2().
clearTimeout2(id)| Parameter | Type | Description |
|---|---|---|
id |
String |
The name of the timer. |
Returns Boolean true when a timer was waiting.
The callback of the timer does not run.
if (clearTimeout2('save' + doc.id))
console.log('The pending save was canceled');
method
CLEANUP(stream, [callback])
Calls a function when a stream is done and destroys the stream.
CLEANUP(stream, [callback])| Parameter | Type | Description |
|---|---|---|
stream |
Stream |
A readable or writable stream. |
callback? |
Function |
Called when the stream is done. |
Returns Promise Without a callback.
The callback runs once, on the first of end, finish, close, aborted or error (for a response, also when its socket closes or fails). The stream is destroyed and its open file descriptor closed at that moment. Without a callback, returns a promise. F.cleanup() is the same method.
var writer = F.Fs.createWriteStream(PATH.temp('export.csv'));
writer.end('id;name\n');
CLEANUP(writer, function() {
console.log('Written');
});
await CLEANUP(writer);
method
PAUSESERVER(name, [enable])
Pauses all incoming traffic under a name.
PAUSESERVER(name, [enable])| Parameter | Type | Description |
|---|---|---|
name |
String |
A name of the reason, shown on the page. |
enable? |
Boolean |
true to pause, false to resume; toggles when omitted. |
Returns Boolean true when the name is paused after the call.
While at least one name is paused, every HTTP request gets the status 503: browsers see a "Please wait" page with the paused names that reloads itself after 10 seconds, XHR requests get an error response, and new WebSocket connections are closed. enable true adds the name, false removes it; without enable the name is toggled. F.pauseserver() is the same method.
PAUSESERVER('Database migration', true);
migrate(function() {
PAUSESERVER('Database migration', false);
});
property
F.paused
The names paused with PAUSESERVER().
F.pausedReturns Array
An array of strings. The server answers with 503 while it is not empty.
if (F.paused.length)
console.log('Paused:', F.paused.join(', '));
event
ON('ready', function() {})
The application is loaded.
ON('ready', function() {})Emitted after the configuration, modules, actions, controllers, plugins and the other parts are loaded and the service timer is started. A listener added after that moment runs at once.
ON('ready', function() {
console.log('Ready on port', CONF.$port);
});
event
ON('load', function() {})
Emitted right after ready.
ON('load', function() {})Emitted once after ready, when the load of the application is complete. Unlike ready, a listener added later is not called.
ON('load', function() {
console.log('Loaded');
});
event
ON('service', function(counter) {})
Emitted once a minute by the service timer.
ON('service', function(counter) {})| Parameter | Type | Description |
|---|---|---|
counter |
Number |
Minutes since the start. |
Emitted after the housekeeping of the minute and after the crons have run. counter is the number of minutes since the start: 1, 2, 3…; use counter % n for longer steps.
ON('service', function(counter) {
if (counter % 10 === 0)
refresh();
});
event
ON('exit', function(signal) {})
The process is stopping.
ON('exit', function(signal) {})| Parameter | Type | Description |
|---|---|---|
signal |
Number |
The signal passed to F.exit(); 15 by default. |
Emitted by F.exit() on SIGTERM, SIGINT, the exit of the process or a stop message from the parent, after workers and FlowStreams are stopped. Work done in the listener must be synchronous: the process ends right after it.
ON('exit', function(signal) {
console.log('Exit', signal);
});
event
ON('error', function(obj) {})
The framework logged an error.
ON('error', function(obj) {})| Parameter | Type | Description |
|---|---|---|
obj |
Object |
{ error: String, name: String, url: String, date: Date }. |
Emitted by the default DEF.onError for every error passed to F.error() and for unhandled exceptions and rejections. obj is { error, name, url, date }, where error is the error as a string. The last 10 errors are also in F.errors.
ON('error', function(obj) {
console.log(obj.date, obj.name, obj.error, obj.url);
});
event
ON('request', function(ctrl) {})
An HTTP request arrived.
ON('request', function(ctrl) {})| Parameter | Type | Description |
|---|---|---|
ctrl |
Controller |
The controller of the request. |
Emitted for every HTTP request before CORS and routing. Requests stopped earlier (a paused server, a blocked IP address, the request limit, a proxy) do not reach it. ctrl is the controller of the request. Call ctrl.cancel() to stop the processing and answer the request yourself.
ON('request', function(ctrl) {
if (ctrl.url === '/health/') {
ctrl.cancel();
ctrl.text('OK');
}
});
event
ON('controller', function(ctrl) {})
A route was found for an HTTP request.
ON('controller', function(ctrl) {})| Parameter | Type | Description |
|---|---|---|
ctrl |
Controller |
The controller of the request. |
Emitted after the route is found and the body is parsed, just before the action of the route runs (also for API routes). ctrl.route is the route. Call ctrl.cancel() to stop the processing and answer the request yourself.
ON('controller', function(ctrl) {
console.log(ctrl.method, ctrl.url);
});
event
ON('componentator', function(meta) {})
COMPONENTATOR() is about to download components.
ON('componentator', function(meta) {})| Parameter | Type | Description |
|---|---|---|
meta |
Object |
{ name: String, components: String }. |
meta is { name, components }. Change meta.components to change the list of components that is downloaded.
ON('componentator', function(meta) {
meta.components += ',exec';
});
event
ON('flowstream_error', function(meta) {})
A component of a FlowStream failed.
ON('flowstream_error', function(meta) {})| Parameter | Type | Description |
|---|---|---|
meta |
Object |
{ id, name, error, source, instanceid, componentid }. |
Emitted for errors of FlowStream components, after the error is printed to the console. meta is { id, name, error, source, instanceid, componentid }: the FlowStream, its name, the error, where it happened and the instance and component.
ON('flowstream_error', function(meta) {
console.log(meta.name, meta.componentid, meta.error);
});
event
ON('flowstream', function(instance) {})
since 0.0.16
A FlowStream instance was created.
ON('flowstream', function(instance) {})| Parameter | Type | Description |
|---|---|---|
instance |
Object |
The FlowStream instance. |
Emitted when a FlowStream is created, in the main process or in a worker; instance is the object you control the FlowStream with. See FlowStream.
ON('flowstream', function(instance) {
console.log('FlowStream', instance.id);
});
event
ON('$mail', function(message) {})
An e-mail is being sent.
ON('$mail', function(message) {})| Parameter | Type | Description |
|---|---|---|
message |
Object |
The mail message. |
Emitted for each message just before it is written to the SMTP connection. message is the mail message (subject, body, email_to, email_from…). See Mail.
ON('$mail', function(message) {
console.log('Mail', message.subject, message.email_to);
});
event
ON('$stats', function(stats) {})
The usage statistics of the process were updated.
ON('$stats', function(stats) {})| Parameter | Type | Description |
|---|---|---|
stats |
Object |
The statistics of the process. |
Emitted 5 seconds after the application is loaded and then once a minute by the service timer, each time after the statistics of the last minute are computed. stats is the same object every time; read it, do not keep a reference to its values.
The main fields: id and pid (the process), date, memory (used heap in MB), requests, pending, errors, timeouts, online (WebSocket clients), download and upload (MB in total), lasterror, lasttimeout, uptime (minutes since the start), overload (how many hours the process was overloaded), mode (debug or release) and version (node, total, build, app). Fields ending with m count the last minute: rm requests, fm files, wm WebSocket messages, em external requests, mm e-mails, om opened files, dm/um downloaded/uploaded MB, pm/sm published/subscribed messages, cm calls, dbrm/dbwm database reads/writes.
ON('$stats', function(stats) {
if (stats.memory > 500)
console.log('High memory', stats.memory, 'MB');
});
event
ON('$message', function(msg, handle) {})
The process received a message from its parent.
ON('$message', function(msg, handle) {})| Parameter | Type | Description |
|---|---|---|
msg |
Object |
The message. |
handle |
Object |
The handle sent with the message, if any. |
Emitted for every message that arrives through process.on('message'), after the framework handled its own messages (total:..., stop). Useful when the application runs as a child process or in a cluster.
ON('$message', function(msg) {
if (msg && msg.type === 'reload')
reload();
});
event
ON('$update', function() {})
Another process of the cluster asked for an update.
ON('$update', function() {})Emitted when the process receives the message total:update. In a cluster, a process that sends process.send('total:update') makes the main process forward it to the other ready processes, so each of them can reload its data.
// the process that changed the data
process.send && process.send('total:update');
// all other processes
ON('$update', function() {
reloadsettings();
});