Spanish Total.js
English
Documentation For AI agents
Contents

Scheduling and events

CRON(), ON(), ONCE(), OFF(), EMIT(), the built-in events, setTimeout2(), CLEANUP() and PAUSESERVER().

.md GitHub
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.
ParameterTypeDescription
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).

Every day at 03:00
CRON('0 3 * * *', function(date) {
	NOSQL('logs').remove().where('date', '<', date.add('-30 days'));
});
Working days
CRON('30 8 * * mo-fr', function() {
	MAIL(CONF.mail_report, 'Daily report', 'mail/report', {});
});
Every 15 minutes
CRON('*/15 * * * *', function() {
	// at minutes 0, 15, 30 and 45
});
method

cron.remove()

Stops a cron.

Removes the cron returned by CRON() from F.crons, so it does not run any more.

Run once
var cron = CRON('0 12 * * *', function() {
	sendreport();
	cron.remove();
});
property

F.crons

The registered crons.

Returns 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().

Count
console.log(F.crons.length + ' crons');
method

ON(name, fn)

Adds a listener of a global event.
ParameterTypeDescription
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.

Own event
ON('order.created', function(order) {
	console.log('New order', order.id);
});
Several events
ON('ready + service', function() {
	refreshcache();
});
method

ONCE(name, fn)

Adds a listener that runs only once.
ParameterTypeDescription
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.

First minute
ONCE('service', function() {
	console.log('The first minute has passed');
});
method

OFF(name, [fn])

Removes a listener of a global event.
ParameterTypeDescription
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.

Remove a listener
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.
ParameterTypeDescription
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
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).
ParameterTypeDescription
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.

Save once after changes
function changed(doc) {
	setTimeout2('save' + doc.id, function() {
		NOSQL('docs').modify(doc).where('id', doc.id);
	}, 2000);
}
With a limit
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().
ParameterTypeDescription
id String The name of the timer.

Returns Boolean true when a timer was waiting.

The callback of the timer does not run.

Cancel
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.
ParameterTypeDescription
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.

Wait for a file
var writer = F.Fs.createWriteStream(PATH.temp('export.csv'));
writer.end('id;name\n');
CLEANUP(writer, function() {
	console.log('Written');
});
With await
await CLEANUP(writer);
method

PAUSESERVER(name, [enable])

Pauses all incoming traffic under a name.
ParameterTypeDescription
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.

During a migration
PAUSESERVER('Database migration', true);

migrate(function() {
	PAUSESERVER('Database migration', false);
});
property

F.paused

The names paused with PAUSESERVER().

Returns Array

An array of strings. The server answers with 503 while it is not empty.

Check
if (F.paused.length)
	console.log('Paused:', F.paused.join(', '));
event

ON('ready', function() {})

The application is loaded.

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.

Start
ON('ready', function() {
	console.log('Ready on port', CONF.$port);
});
event

ON('load', function() {})

Emitted right after ready.

Emitted once after ready, when the load of the application is complete. Unlike ready, a listener added later is not called.

Load
ON('load', function() {
	console.log('Loaded');
});
event

ON('service', function(counter) {})

Emitted once a minute by the service timer.
ParameterTypeDescription
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.

Every 10 minutes
ON('service', function(counter) {
	if (counter % 10 === 0)
		refresh();
});
event

ON('exit', function(signal) {})

The process is stopping.
ParameterTypeDescription
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.

Last log
ON('exit', function(signal) {
	console.log('Exit', signal);
});
event

ON('error', function(obj) {})

The framework logged an error.
ParameterTypeDescription
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.

Send errors elsewhere
ON('error', function(obj) {
	console.log(obj.date, obj.name, obj.error, obj.url);
});
event

ON('request', function(ctrl) {})

An HTTP request arrived.
ParameterTypeDescription
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.

Health check
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.
ParameterTypeDescription
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.

Log routes
ON('controller', function(ctrl) {
	console.log(ctrl.method, ctrl.url);
});
event

ON('componentator', function(meta) {})

COMPONENTATOR() is about to download components.
ParameterTypeDescription
meta Object { name: String, components: String }.

meta is { name, components }. Change meta.components to change the list of components that is downloaded.

Add a component
ON('componentator', function(meta) {
	meta.components += ',exec';
});
event

ON('flowstream_error', function(meta) {})

A component of a FlowStream failed.
ParameterTypeDescription
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.

Log
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.
ParameterTypeDescription
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.

Log
ON('flowstream', function(instance) {
	console.log('FlowStream', instance.id);
});
event

ON('$mail', function(message) {})

An e-mail is being sent.
ParameterTypeDescription
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.

Log
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.
ParameterTypeDescription
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.

Watch memory
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.
ParameterTypeDescription
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.

Command
ON('$message', function(msg) {
	if (msg && msg.type === 'reload')
		reload();
});
event

ON('$update', function() {})

Another process of the cluster asked for an update.

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.

Keep a cluster in sync
// the process that changed the data
process.send && process.send('total:update');

// all other processes
ON('$update', function() {
	reloadsettings();
});
Made in Europe