Scheduling and events
Crons, global events, the events of the framework, debounced timers, pausing the server and the service timer.
On this page
A Total.js 5 application has one internal timer, the service timer, that runs every 5 seconds from the moment the application is loaded. Once a minute it does the housekeeping of the framework, runs the crons registered with CRON() and emits the service event. The framework also emits global events (ready, exit, request…) that you catch with ON(), and you can emit your own events with EMIT().
// /modules/tasks.js
exports.install = function() {
ON('ready', function() {
console.log('The application is loaded');
});
CRON('0 3 * * *', function(date) {
// every day at 03:00
NOSQL('logs').remove().where('date', '<', date.add('-30 days'));
});
};Crons
CRON(line, fn) registers a function that runs when the current date matches the cron line. The line has five fields separated by spaces, in this order:
| Field | Values |
|---|---|
| minute | 0–59 |
| hour | 0–23 |
| day of the month | 1–31 |
| month | 1–12 |
| day of the week | 0–6 (0 is Sunday) or a name: su, mo, tu, we, th, fr, sa |
Each field accepts:
*: any value,- a number:
30, - a list:
0,15,30,45, - a range:
8-17(both ends included), - a step:
*/15is every 15th value from the first value of the field (0for minutes and hours,1for days and months),5/20every 20th value from5.
Names of days can be written in full (monday): only the first two letters are read.
CRON('30 8 * * mo-fr', function(date) {
// at 08:30 from Monday to Friday
});
CRON('0,30 * * * *', function() {
// every half hour
});
CRON('0 0 1 * *', function() {
// at midnight on the first day of every month
});
CRON('5/20 8-17 * * mo-fr', function() {
// at minutes 5, 25 and 45 from 08:00 to 17:59 on working days
});The crons are checked once a minute by the service timer, with the date in NOW, and fn gets that date as its argument. The minutes are counted from the start of the application, not from the start of a wall-clock minute, so a cron runs within the minute it matches, not at its first second. Hours and days follow the time zone of the process, which is $timezone from the configuration (default utc).
CRON() returns an object; call its remove() method to stop the cron. All registered crons are in the array F.crons.
var cron = CRON('* * * * *', function() {
console.log('Every minute');
});
// later
cron.remove();Events
ON(name, fn) adds a listener, ONCE(name, fn) adds a listener that is removed after its first call, OFF(name, [fn]) removes one listener or all listeners of the event, and EMIT(name, [a], [b], ...) calls the listeners with up to seven arguments. They are global forms of F.on(), F.once(), F.off() and F.emit(); inside a listener this is F.
ON('order.created', function(order) {
MAIL(order.email, 'Thank you', 'mail/order', order);
});
// anywhere
EMIT('order.created', { id: 123, email: 'buyer@example.com' });One listener can catch several events: join their names with +.
ON('ready + service', function() {
// once at the start, then once a minute
});A listener of ready added after the application is loaded runs at once, so ON('ready') is safe in code that loads late (plugins, code run from a cron).
OFF(name, fn) needs the same function that was passed to ON(); OFF(name) removes every listener of name, including the ones of the framework, so use it only for your own events.
Built-in events
| Event | Arguments | When |
|---|---|---|
ready | The application is loaded (all modules, actions, controllers…) | |
load | Right after ready | |
service | counter | Once a minute; counter is the number of minutes since the start |
exit | signal | The process is stopping |
error | obj | The framework logged an error |
request | ctrl | An HTTP request arrived, before routing |
controller | ctrl | A route was found, before its action runs |
componentator | meta | COMPONENTATOR() is about to download components |
flowstream_error | meta | A component of a FlowStream failed |
flowstream | instance | A FlowStream instance was created |
$mail | message | An e-mail is being sent |
$stats | stats | The usage statistics of the process were updated |
$message | msg, handle | The process received a message from its parent |
$update | Another process of the cluster sent total:update |
Other pages describe the events of their area: $reconfigure in Configuration, $view in Views, websocket_end in WebSockets, and the @{action} events in Actions. $cors and $tms are used inside the framework.
The request and controller events can stop the request: call ctrl.cancel() and answer it yourself.
ON('request', function(ctrl) {
if (ctrl.url === '/health/') {
ctrl.cancel();
ctrl.text('OK');
}
});Debounced timers
setTimeout2(id, callback, timeout) is a setTimeout() with a name. When it is called again with the same id before the time passes, the previous timer is canceled and a new one starts with the new callback. The callback runs only after timeout milliseconds without a new call, which is a debounce. clearTimeout2(id) cancels the timer and returns true when one was waiting.
function save(doc) {
// many changes in a short time make one write
setTimeout2('save' + doc.id, function() {
NOSQL('docs').modify(doc).where('id', doc.id);
}, 2000);
}The fourth argument limit stops endless postponing: after limit postponements, the next call runs its callback at once and the counting starts again.
setTimeout2('search', function() {
search(text);
}, 300, 10);Waiting for a stream
CLEANUP(stream, [callback]) calls callback once, when the stream ends, finishes, closes, is aborted or fails, and destroys the stream at that moment. Without a callback it returns a promise.
var writer = F.Fs.createWriteStream(PATH.temp('export.csv'));
writer.write('id;name\n');
writer.end();
CLEANUP(writer, function() {
console.log('Written');
});Pausing the server
PAUSESERVER(name, [enable]) holds all incoming traffic while something is not ready, for example a migration. While at least one name is paused, HTTP requests get the status 503: browsers see a "Please wait" page that lists the paused names and reloads itself after 10 seconds, XHR requests get an error response, and new WebSocket connections are closed. Static files are paused too.
PAUSESERVER('Database migration', true);
migrate(function() {
PAUSESERVER('Database migration', false);
});Without enable the call toggles the name and returns true when it is now paused. The paused names are in the array F.paused.
The service timer
Every 5 seconds the timer updates NOW and cancels HTTP requests that ran out of time. Once a minute it:
- removes expired items of the cache and the bans that expired,
- every 5 minutes clears
TEMP, - every
$clearcacheminutes (default10) clears the internal caches of actions, views, paths, images and templates, - every
$tmsclearblockedminutes (default60) clears the list of blocked TMS clients, - updates the usage statistics and emits
$stats, - runs the crons and emits
service.
$clearcache and $tmsclearblocked are keys of the config file; see Configuration. For work that repeats in fixed steps, a cron with * in a field, or the service event with the counter, is enough:
ON('service', function(counter) {
if (counter % 5 === 0) {
// every 5 minutes
refresh();
}
});