Spanish Total.js
English
Documentation For AI agents
Contents

Scheduling and events

SCHEDULE(), the event functions, every built-in event and the timing helpers.

.md GitHub
On this page

The scheduler SCHEDULE(), the event functions ON(), ONCE(), OFF(), EMIT() and EMIT2(), every built-in framework event, and the timing helpers WAIT(), setTimeout2(), clearTimeout2(), PAUSESERVER() and CLEANUP(). The guide Scheduling and events explains how to use them with examples; this page is the exact reference.

API

method

SCHEDULE(date, [repeat], fn)

Registers a job that runs at a time, repeatedly, or by a cron expression.
ParameterTypeDescription
date String|Number|Date A cron expression, a date or time string, a timestamp or a Date.
repeat? String A repeat period such as '1 day' or 'each hour'. Not used with a cron expression.
fn Function The job. It gets no arguments.

Returns Object The job, with id, remove() and exec().

The framework checks the jobs once a minute, in its service, so a job runs on the first check at or after its time.

  • A string with a space is a cron expression with five fields (minute, hour, day of month, month, day of week). The job runs at every minute that matches; it takes no repeat.
  • A string without a space is parsed as a date or time (for example '03:00') in the application time zone (default_timezone). If it has already passed and repeat is set, the first run moves forward by one repeat.
  • A number is a timestamp in milliseconds; a Date is used as it is.

repeat is a period for Date.add(), such as '5 minutes' or '1 day'; the word each is read as 1 ('each day'). Without repeat a date job runs once and is then removed.

Cron fields accept *, a number, a list (1,15,30) and a range (9-17). Days of the week are 0-6 (Sunday is 0) or names, of which only the first two letters count (su, mo, tu, we, th, fr, sa).

Every day at 03:00
SCHEDULE('03:00', '1 day', function() {
	console.log('Nightly cleanup');
});
Cron: working days at 08:00
SCHEDULE('0 8 * * mo-fr', function() {
	console.log('Good morning');
});
Once at a specific date
SCHEDULE(new Date(2026, 11, 24, 8, 0), function() {
	console.log('Christmas Eve');
});
property

schedule.id

The identifier of the job.

Returns String

A short random string that SCHEDULE() creates for each job.

method

schedule.remove()

Stops the job and removes it from the scheduler.

Use it to stop a repeating or cron job. A one-time job removes itself after it runs.

Stop after the first run
var job = SCHEDULE('0,30 * * * *', function() {
	console.log('Run');
	job.remove();
});
method

schedule.exec()

Runs the job now.

Calls the job function immediately. The planned time of the next run does not change.

Run at start and then every hour
var job = SCHEDULE('0 * * * *', refresh);

ON('ready', function() {
	job.exec();
});
method

ON(name, fn)

Adds a listener to an event.
ParameterTypeDescription
name String The event name.
fn Function The listener.

fn is called with the arguments of EMIT(), and this is the framework. Listeners run in the order they were added.

For init, load and ready, if the application has already loaded, fn is called immediately (and is not stored).

React to the start
ON('ready', function() {
	console.log('Listening on port', F.port);
});
method

ONCE(name, fn)

Adds a listener that is removed after its first call.
ParameterTypeDescription
name String The event name.
fn Function The listener.

Works like ON(); the listener is removed after the first EMIT() of the event.

First request only
ONCE('request', function(req) {
	console.log('First request from', req.ip);
});
method

OFF([name], [fn])

Removes event listeners.
ParameterTypeDescription
name? String The event name.
fn? Function The listener to remove.
  • OFF(name, fn) removes that one listener. It must be the same function you passed to ON().
  • OFF(name) removes all listeners of the event, including the framework's own.
  • OFF() removes all listeners of all events.
Remove one listener
function log(req, res) {
	console.log(req.url);
}

ON('request', log);
OFF('request', log);
method

EMIT(name, [a], [b], [c], [d], [e], [f], [g])

Calls all listeners of an event in the current process.
ParameterTypeDescription
name String The event name.
a...g? Object Up to seven arguments for the listeners.

Passes up to seven arguments. The listeners run synchronously, in the order they were added. Listeners added with ONCE() are removed afterwards. An event without listeners does nothing.

Your own event
ON('order_created', function(order) {
	console.log('New order', order.id);
});

EMIT('order_created', { id: 'A100' });
method

EMIT2(name, [a], [b], [c], [d], [e])

Sends an event to the other processes of the application.
ParameterTypeDescription
name String The event name.
a...e? Object Up to five serialisable arguments.

The event goes to the threads (from the main process, which also calls its own listeners), to the cluster, or from a thread or worker back to its parent. Up to five arguments, sent as IPC messages, so use plain serialisable values. In a single process without threads or a cluster nothing happens; use EMIT() there.

Clear a cache in every process
ON('products_changed', function() {
	CACHE.remove('products');
});

EMIT2('products_changed');
method

WAIT(validator, callback, [timeout], [interval])

Waits until a condition is true.
ParameterTypeDescription
validator Function Returns true when the wait is over.
callback Function function(err, success).
timeout? Number Maximum wait in milliseconds. Default: 5000
interval? Number Check interval in milliseconds. Default: 500

If validator() already returns true, callback(null, true) runs immediately. Otherwise validator() is checked every interval ms. When it returns true the callback gets (null, true); after timeout ms it gets (Error("Timeout"), false).

Wait for a connection
WAIT(() => MAIN.client != null, function(err) {
	if (err)
		console.log('Not connected');
	else
		MAIN.client.send('hello');
}, 10000);
method

setTimeout2(name, fn, timeout, [limit], [param])

A named timeout: each call with the same name restarts the timer.
ParameterTypeDescription
name String The name of the timer.
fn Function function(param).
timeout Number Delay in milliseconds.
limit? Number Maximum number of postponements before fn runs at once.
param? Object An argument for fn.

Returns Timeout The Node.js timer, or nothing when fn ran immediately.

Cancels the previous timer of the same name and starts a new one, so fn runs once, timeout ms after the last call (a debounce). With limit, after limit postponements fn runs immediately (without param) and the counter resets. param is passed to fn.

Save once after a burst of changes
function changed() {
	setTimeout2('save', save, 2000);
}

function save() {
	F.Fs.writeFile(PATH.databases('state.json'), JSON.stringify(MAIN.state), NOOP);
}
method

clearTimeout2(name)

Cancels a timer created by setTimeout2().
ParameterTypeDescription
name String The name used in setTimeout2().

Returns Boolean true if a timer was cancelled.

Returns true if a pending timer with that name was cancelled.

Cancel
setTimeout2('save', save, 5000);
clearTimeout2('save');
method

PAUSESERVER(name, [enable])

Pauses the server: every request gets 503 while a name is paused.
ParameterTypeDescription
name String A name for the pause.
enable? Boolean true pauses, false resumes. When omitted, the state toggles.

Returns Boolean true if name is now paused.

Each name is one reason to pause. While at least one name is paused, HTTP requests are answered with 503 and WebSocket upgrades are refused. With enable the state is set; without it the state of name is toggled. F.wait() is the same function.

Pause during a migration
PAUSESERVER('migration', true);
migrate(function() {
	PAUSESERVER('migration', false);
});
config

default_interval_clear_cache : 10

Minutes between clean-ups of the temporary file and view cache.

Returns Number

Counted in service ticks (one per minute). Each clean-up emits clear with the type 'temporary'.

config

default_interval_clear_resources : 20

Minutes between clean-ups of the loaded resources.

Returns Number

Counted in service ticks. Each clean-up emits clear with the type 'resources'.

config

default_interval_clear_dnscache : 30

Minutes between clean-ups of the DNS cache.

Returns Number

Counted in service ticks. Each clean-up emits clear with the type 'dns'.

event

ON('init', function())

Configuration is loaded; the application files are not loaded yet.

Emitted once at start, before definitions, models, controllers and the other files load. If you call ON('init') after the application has loaded, the function runs immediately.

Listen
ON('init', function() {
	console.log('Config ready, port', CONF.port);
});
event

ON('load', function())

All application files are loaded.

Emitted once, right before ready. If the application has already loaded, the function runs immediately.

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

ON('ready', function())

The application is ready.

Emitted once after load, when all files are loaded. The usual place for start-up code. If the application has already loaded, the function runs immediately.

Listen
ON('ready', function() {
	MAIN.started = NOW;
});
event

ON('service', function(counter))

Emitted every minute by the framework service.
ParameterTypeDescription
counter Number The number of service runs.

counter is the number of runs since the application started (1, 2, 3...). Use the remainder to run code every few minutes. In a worker, adding this listener starts the timer.

Listen
ON('service', function(counter) {
	if (counter % 10 === 0)
		console.log('Ten more minutes');
});
event

ON('exit', function(signal))

The application is stopping.
ParameterTypeDescription
signal Number|String The signal; 15 (SIGTERM) when none was given.

Emitted once when the framework stops, after it has sent the signal to its workers and threads. Keep the work synchronous; the process ends soon after.

Listen
ON('exit', function(signal) {
	console.log('Stopping with signal', signal);
});
event

ON('request', function(req, res))

A request arrived, before routing.
ParameterTypeDescription
req Request The request.
res Response The response.

Emitted for each HTTP request after the proxies are checked and before redirects and routing.

Listen
ON('request', function(req, res) {
	console.log(req.method, req.url);
});
event

ON('request_begin', function(req, res))

The request is prepared for routing.
ParameterTypeDescription
req Request The request.
res Response The response.

Emitted after the request has been parsed (headers, XHR flag), before the route is looked up.

Listen
ON('request_begin', function(req) {
	req.started = Date.now();
});
event

ON('request_end', function(req, res))

The response to a request has finished.
ParameterTypeDescription
req Request The request.
res Response The response.

Emitted when the framework has finished sending a response.

Listen
ON('request_end', function(req, res) {
	console.log(req.url, Date.now() - req.started, 'ms');
});
event

ON('controller', function(controller, name, options))

A route action is about to run.
ParameterTypeDescription
controller Controller The controller of the request.
name String The controller name.
options Object The custom options of the route.

Emitted before the action of a route runs. Call controller.cancel() to stop the action here. name is the name of the controller file that declared the route.

Listen
ON('controller', function(controller, name) {
	controller.repository.section = name;
});
event

ON('@name', function(controller, name, options))

A route action of one controller is about to run.
ParameterTypeDescription
controller Controller The controller of the request.
name String The controller name.
options Object The custom options of the route.

Like controller, but only for routes declared in the controller file name: ON('@admin') runs for the routes in controllers/admin.js.

Listen
ON('@admin', function(controller) {
	controller.layout('layout_admin');
});
event

ON('errornnn', function(req, res, exception))

An error response is sent, for example error404.
ParameterTypeDescription
req Request The request.
res Response The response.
exception Error The problem, if any.

The name is error plus the HTTP status: error400, error401, error404, error500... Emitted when the framework answers with that status.

Listen
ON('error404', function(req) {
	console.log('Not found:', req.url);
});
event

ON('error', function(obj))

The framework logged an error.
ParameterTypeDescription
obj Object { error, name, url, date }.

Emitted by the default DEF.onError handler for each error it records. The last five errors are also kept in F.errors.

Listen
ON('error', function(obj) {
	console.log(obj.name, obj.error);
});
event

ON('route', function(type, route))

A route was registered.
ParameterTypeDescription
type String web, websocket or file.
route Object The internal route object.

type is 'web' for ROUTE() routes, 'websocket' for WebSocket routes and 'file' for file routes.

Listen
ON('route', function(type) {
	console.log('A new route of type', type);
});
event

ON('install', function(type, name, module))

A file of the application was installed.
ParameterTypeDescription
type String For example 'controller' or 'model'.
name String The name of the file.
module Object The exports of the file.

Emitted after the framework installs a controller, model, definition, plugin, module, source and other types. module is what the file exports.

Listen
ON('install', function(type, name) {
	console.log('Installed', type, name);
});
event

ON('configure', function(CONF))

The configuration was loaded.
ParameterTypeDescription
CONF Object The configuration.

Emitted each time the configuration files are read, at start and on reload.

Listen
ON('configure', function(conf) {
	console.log('Name:', conf.name);
});
event

ON('update', function(err))

UPDATE() has finished.
ParameterTypeDescription
err ErrorBuilder The errors, or null.

Emitted when the update scripts of UPDATE() have run, with the errors if any.

Listen
ON('update', function(err) {
	err && console.log('Update failed', err);
});
event

ON('clear', function(type, [value]))

An internal cache was cleared.
ParameterTypeDescription
type String temporary, resources or dns.
value? Object The temporary storage, for temporary only.

type is 'temporary' (with the temporary storage as value), 'resources' or 'dns'. The service clears them by the default_interval_clear_* settings.

Listen
ON('clear', function(type) {
	console.log('Cleared', type);
});
event

ON('cache_set', function(key, value, expire, sync))

A value was stored with CACHE.
ParameterTypeDescription
key String The key.
value Object The value.
expire Date The expiration.
sync Boolean An internal flag for synchronised caches.

Emitted by CACHE.set().

Listen
ON('cache_set', function(key) {
	console.log('Cached', key);
});
event

ON('cache_expired', function(key, value))

A CACHE value expired.
ParameterTypeDescription
key String The key.
value Object The expired value.

Emitted when the cache removes an expired item (checked every minute) or finds one when reading it.

Listen
ON('cache_expired', function(key) {
	console.log('Expired', key);
});
event

ON('controller_render_meta', function(controller))

A view is about to print its meta tags.
ParameterTypeDescription
controller Controller The controller that renders the view.

Emitted when a layout renders @{meta}, before the tags are built. Change controller.repository here to adjust them.

Listen
ON('controller_render_meta', function(controller) {
	if (!controller.repository.title)
		controller.repository.title = CONF.name;
});
event

ON('websocket', function(req, socket, head))

A WebSocket upgrade request arrived.
ParameterTypeDescription
req Request The request.
socket Socket The network socket.
head Buffer The first packet of the upgraded stream.

Emitted after a matching WebSocket route was found, before the connection is accepted.

Listen
ON('websocket', function(req) {
	console.log('WebSocket from', req.ip);
});
event

ON('websocket_begin', function(controller, client))

A WebSocket client connected.
ParameterTypeDescription
controller WebSocket The WebSocket controller.
client WebSocketClient The client.

Emitted when a client is added to its WebSocket controller, before its open event.

Listen
ON('websocket_begin', function(controller, client) {
	console.log('Online:', controller.online);
});
event

ON('websocket_end', function(controller, client))

A WebSocket client disconnected.
ParameterTypeDescription
controller WebSocket The WebSocket controller.
client WebSocketClient The client.

Emitted when a client is removed from its WebSocket controller.

Listen
ON('websocket_end', function(controller, client) {
	console.log('Left:', client.id);
});
event

ON('componentator', function(meta))

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

meta holds name and components from the COMPONENTATOR() call.

Listen
ON('componentator', function(meta) {
	console.log('Components', meta.name);
});
event

ON('mail', function(message))

An email message is being sent.
ParameterTypeDescription
message MailMessage The message.

Emitted for each message as the SMTP sender writes it.

Listen
ON('mail', function(message) {
	console.log('Mail:', message.subject);
});
event

ON('message', function(msg, handle))

The process received an IPC message.
ParameterTypeDescription
msg Object The message.
handle Object The handle sent with the message, if any.

Emitted for every message the process gets from its parent (process.on('message')), after the framework has handled its own.

Listen
ON('message', function(msg) {
	if (msg.type === 'reload')
		console.log('Reload requested');
});
event

ON('watcher', function(app))

The watcher (re)started the application.
ParameterTypeDescription
app ChildProcess The application process, or null.

Emitted in the main process of debug or release mode with the file watcher, each time it starts the application process.

Listen
ON('watcher', function(app) {
	app && console.log('App PID', app.pid);
});
event

ON('debug_start', function())

The application started in debug mode.

Emitted in the application process when it starts the first time in debug mode.

Listen
ON('debug_start', function() {
	console.log('Debug start');
});
event

ON('debug_restart', function())

The application restarted in debug mode.

Emitted instead of debug_start when the debug watcher restarts the application after a change.

Listen
ON('debug_restart', function() {
	console.log('Restarted after a change');
});
method

CLEANUP(stream, [callback])

since 0.0.96 Destroys a stream after it has finished.
ParameterTypeDescription
stream Stream A readable or writable stream.
callback? Function Called after the stream is destroyed.

Returns Promise Only when callback is not set.

Waits until the stream finishes or fails, destroys it and calls callback. Without a callback it returns a Promise.

Close a file after piping
var stream = F.Fs.createReadStream(PATH.databases('export.csv'));
stream.pipe(F.Fs.createWriteStream(PATH.temp('export.csv')));

CLEANUP(stream, function() {
	console.log('Done');
});
With await
async function copy(stream) {
	await CLEANUP(stream);
	console.log('Closed');
}
Made in Europe