Scheduling and events
Run jobs at a time, by cron or every few minutes, and react to framework events with ON() and EMIT().
On this page
Total.js 4 runs a service once a minute. It clears caches, fires the service event and starts the jobs you registered with SCHEDULE(). Framework events let your code react to the life of the application: start, requests, errors, exit. This guide shows both. The exact signatures are in the reference Scheduling and events.
Run code at a set time
SCHEDULE(date, [repeat], fn) registers a job. The date can be a time, a Date, a timestamp in milliseconds or a cron expression.
// definitions/jobs.js
// Every day at 03:00
SCHEDULE('03:00', '1 day', function() {
console.log('Nightly cleanup');
});
// Once, in ten minutes
SCHEDULE(Date.now() + 1000 * 60 * 10, function() {
console.log('Ten minutes later');
});- A time such as
'03:00'is today at that time. If that time has already passed and you setrepeat, the first run moves forward by onerepeat(here to tomorrow). repeatis a period thatDate.add()understands:'5 minutes','2 hours','1 day','1 week'. You can write'each'for one:'each day'is the same as'1 day'.- Without
repeatthe job runs once and then removes itself. - Times are read in the time zone of the application, which is the
default_timezonesetting (utcby default).
The service checks the jobs once a minute, so a job runs on the first check at or after its time. Do not expect precision below one minute.
A string that contains a space is always read as a cron expression. To run a job once at a specific date, pass a Date object or a timestamp:
SCHEDULE(new Date(2026, 11, 24, 8, 0), function() {
console.log('Christmas Eve, 08:00');
});Cron expressions
A cron expression has five fields separated by spaces: minute, hour, day of month, month (1-12) and day of week.
// At 02:30 every day
SCHEDULE('30 2 * * *', backup);
// At 08:00 from Monday to Friday
SCHEDULE('0 8 * * mo-fr', report);
// At 00 and 30 minutes of every hour
SCHEDULE('0,30 * * * *', sync);| Field value | Meaning |
|---|---|
* | any value |
5 | exactly 5 |
1,15,30 | one of the listed values |
9-17 | any value between 9 and 17, both included |
Days of the week are numbers from 0 (Sunday) to 6 (Saturday), or names. Only the first two letters of a name count: su, mo, tu, we, th, fr, sa (so monday also works).
A cron job has no repeat argument. It runs at every minute that matches the expression, until you remove it. To run a job every few minutes, list the minutes ('0,15,30,45 * * * *') or use a time with repeat (SCHEDULE('00:00', '15 minutes', fn)).
Stop or trigger a job
SCHEDULE() returns the job. Keep it to stop the job later or to run it at once:
var job = SCHEDULE('0 * * * *', function() {
console.log('Every full hour');
});
// Run it now, outside its time
job.exec();
// Stop it
job.remove();The service event
If you need something every minute, listen to service. The argument is the number of runs since the application started, so you can derive longer periods:
ON('service', function(counter) {
// Every 5 minutes
if (counter % 5 === 0)
refreshrates();
// Every hour
if (counter % 60 === 0)
cleanold();
});The same tick clears the internal caches. default_interval_clear_cache (10), default_interval_clear_resources (20) and default_interval_clear_dnscache (30) set how many minutes pass between those clean-ups, and each one emits the clear event.
Listen to events
ON(name, fn) adds a listener. ONCE(name, fn) adds one that is removed after its first call. OFF(name, [fn]) removes listeners. this inside a listener is the framework (F).
ON('ready', function() {
console.log('The application is ready');
});
ON('request_end', function(req, res) {
// every finished request
});
ONCE('service', function() {
console.log('The first service tick');
});init, load and ready are special: if the application has already loaded when you call ON(), the function runs immediately. So a plugin or a module that is installed late still gets its ready call.
To remove one listener, pass the same function you added:
function onrequest(req, res) {
console.log(req.method, req.url);
}
ON('request', onrequest);
// later
OFF('request', onrequest);OFF(name) without a function removes every listener of that event, including the framework's own. Call OFF() with no arguments only if you really mean to remove all listeners of all events.
Your own events
Any name works with EMIT(). Use events to let parts of the app talk without requiring each other:
// schemas/orders.js
EMIT('order_created', order);
// definitions/notify.js
ON('order_created', function(order) {
MAIL(order.email, 'Thank you', '@mail/order', order);
});EMIT(name, [a], [b], ...) passes up to seven arguments and calls the listeners synchronously, in the order they were added.
EMIT2(name, [a], ...) sends the event to the other processes of the application: the threads, the cluster, or the parent process of a worker. It passes up to five arguments, so they must be serialisable values. In a single process without threads or a cluster it does nothing; use EMIT() there.
Built-in events
| Event | Arguments | When |
|---|---|---|
init | Configuration is loaded, before the app files load | |
load, ready | All files are loaded; ready comes right after load | |
service | counter | Every minute |
request | req, res | A request arrives, before routing |
request_begin | req, res | The request is prepared for routing |
request_end | req, res | The response has finished |
controller | controller, name, options | Before a route action runs |
errorNNN | req, res, exception | An error page is sent, for example error404 |
error | obj | The framework logs an error |
route | type, route | A route is registered |
install | type, name, module | A file (controller, model, plugin...) is installed |
configure | CONF | Configuration has been (re)loaded |
websocket | req, socket, head | A WebSocket upgrade request arrives |
websocket_begin, websocket_end | controller, client | A WebSocket client connects or disconnects |
clear | type, [value] | An internal cache is cleared |
cache_set, cache_expired | key, value, ... | A CACHE value is set or expires |
mail | message | An email is being sent |
message | msg, handle | The process receives an IPC message |
exit | signal | The application stops |
Each event has its own entry in the reference with the exact arguments.
Clean up streams
CLEANUP(stream, [callback]) waits until a stream has finished, destroys it and then calls the callback. Without a callback it returns a Promise. Use it to release file handles after you pipe a stream:
var stream = F.Fs.createReadStream(PATH.public('big.zip'));
stream.pipe(F.Fs.createWriteStream(PATH.temp('big.zip')));
CLEANUP(stream, function() {
console.log('The file is closed');
});Wait and delay
WAIT(validator, callback, [timeout], [interval]) checks validator() every interval ms (500) until it returns true, or fails after timeout ms (5000):
WAIT(() => MAIN.db != null, function(err) {
if (err)
console.log('The database did not connect in time');
else
console.log('Connected');
}, 10000, 200);setTimeout2(name, fn, timeout, [limit], [param]) is a named timeout. Calling it again with the same name cancels the previous timer, so the function runs once after the last call (a debounce). With limit, after that many postponements the function runs at once. clearTimeout2(name) cancels it.
ON('request_end', function() {
// write statistics 5 s after the last request,
// but at least every 100 requests
setTimeout2('stats', savestats, 5000, 100);
});PAUSESERVER(name, [enable]) makes the server answer every request with 503 while at least one name is paused, for example during a migration.