Scheduling and events
SCHEDULE(), the event functions, every built-in event and the timing helpers.
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.
SCHEDULE(date, [repeat], fn)| Parameter | Type | Description |
|---|---|---|
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 andrepeatis set, the first run moves forward by onerepeat. - 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).
SCHEDULE('03:00', '1 day', function() {
console.log('Nightly cleanup');
});
SCHEDULE('0 8 * * mo-fr', function() {
console.log('Good morning');
});
SCHEDULE(new Date(2026, 11, 24, 8, 0), function() {
console.log('Christmas Eve');
});
property
schedule.id
The identifier of the job.
schedule.idReturns String
A short random string that SCHEDULE() creates for each job.
method
schedule.remove()
Stops the job and removes it from the scheduler.
schedule.remove()Use it to stop a repeating or cron job. A one-time job removes itself after it runs.
var job = SCHEDULE('0,30 * * * *', function() {
console.log('Run');
job.remove();
});
method
schedule.exec()
Runs the job now.
schedule.exec()Calls the job function immediately. The planned time of the next run does not change.
var job = SCHEDULE('0 * * * *', refresh);
ON('ready', function() {
job.exec();
});
method
ON(name, fn)
Adds a listener to an event.
ON(name, fn)| Parameter | Type | Description |
|---|---|---|
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).
ON('ready', function() {
console.log('Listening on port', F.port);
});
method
ONCE(name, fn)
Adds a listener that is removed after its first call.
ONCE(name, fn)| Parameter | Type | Description |
|---|---|---|
name |
String |
The event name. |
fn |
Function |
The listener. |
Works like ON(); the listener is removed after the first EMIT() of the event.
ONCE('request', function(req) {
console.log('First request from', req.ip);
});
method
OFF([name], [fn])
Removes event listeners.
OFF([name], [fn])| Parameter | Type | Description |
|---|---|---|
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 toON().OFF(name)removes all listeners of the event, including the framework's own.OFF()removes all listeners of all events.
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.
EMIT(name, [a], [b], [c], [d], [e], [f], [g])| Parameter | Type | Description |
|---|---|---|
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.
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.
EMIT2(name, [a], [b], [c], [d], [e])| Parameter | Type | Description |
|---|---|---|
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.
ON('products_changed', function() {
CACHE.remove('products');
});
EMIT2('products_changed');
method
WAIT(validator, callback, [timeout], [interval])
Waits until a condition is true.
WAIT(validator, callback, [timeout], [interval])| Parameter | Type | Description |
|---|---|---|
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(() => 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.
setTimeout2(name, fn, timeout, [limit], [param])| Parameter | Type | Description |
|---|---|---|
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.
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().
clearTimeout2(name)| Parameter | Type | Description |
|---|---|---|
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.
setTimeout2('save', save, 5000);
clearTimeout2('save');
method
PAUSESERVER(name, [enable])
Pauses the server: every request gets 503 while a name is paused.
PAUSESERVER(name, [enable])| Parameter | Type | Description |
|---|---|---|
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.
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.
default_interval_clear_cache : 10Returns 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.
default_interval_clear_resources : 20Returns 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.
default_interval_clear_dnscache : 30Returns 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.
ON('init', function())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.
ON('init', function() {
console.log('Config ready, port', CONF.port);
});
event
ON('load', function())
All application files are loaded.
ON('load', function())Emitted once, right before ready. If the application has already loaded, the function runs immediately.
ON('load', function() {
console.log('Loaded');
});
event
ON('ready', function())
The application is ready.
ON('ready', function())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.
ON('ready', function() {
MAIN.started = NOW;
});
event
ON('service', function(counter))
Emitted every minute by the framework service.
ON('service', function(counter))| Parameter | Type | Description |
|---|---|---|
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.
ON('service', function(counter) {
if (counter % 10 === 0)
console.log('Ten more minutes');
});
event
ON('exit', function(signal))
The application is stopping.
ON('exit', function(signal))| Parameter | Type | Description |
|---|---|---|
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.
ON('exit', function(signal) {
console.log('Stopping with signal', signal);
});
event
ON('request', function(req, res))
A request arrived, before routing.
ON('request', function(req, res))| Parameter | Type | Description |
|---|---|---|
req |
Request |
The request. |
res |
Response |
The response. |
Emitted for each HTTP request after the proxies are checked and before redirects and routing.
ON('request', function(req, res) {
console.log(req.method, req.url);
});
event
ON('request_begin', function(req, res))
The request is prepared for routing.
ON('request_begin', function(req, res))| Parameter | Type | Description |
|---|---|---|
req |
Request |
The request. |
res |
Response |
The response. |
Emitted after the request has been parsed (headers, XHR flag), before the route is looked up.
ON('request_begin', function(req) {
req.started = Date.now();
});
event
ON('request_end', function(req, res))
The response to a request has finished.
ON('request_end', function(req, res))| Parameter | Type | Description |
|---|---|---|
req |
Request |
The request. |
res |
Response |
The response. |
Emitted when the framework has finished sending a response.
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.
ON('controller', function(controller, name, options))| Parameter | Type | Description |
|---|---|---|
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.
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.
ON('@name', function(controller, name, options))| Parameter | Type | Description |
|---|---|---|
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.
ON('@admin', function(controller) {
controller.layout('layout_admin');
});
event
ON('errornnn', function(req, res, exception))
An error response is sent, for example error404.
ON('errornnn', function(req, res, exception))| Parameter | Type | Description |
|---|---|---|
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.
ON('error404', function(req) {
console.log('Not found:', req.url);
});
event
ON('error', function(obj))
The framework logged an error.
ON('error', function(obj))| Parameter | Type | Description |
|---|---|---|
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.
ON('error', function(obj) {
console.log(obj.name, obj.error);
});
event
ON('route', function(type, route))
A route was registered.
ON('route', function(type, route))| Parameter | Type | Description |
|---|---|---|
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.
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.
ON('install', function(type, name, module))| Parameter | Type | Description |
|---|---|---|
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.
ON('install', function(type, name) {
console.log('Installed', type, name);
});
event
ON('configure', function(CONF))
The configuration was loaded.
ON('configure', function(CONF))| Parameter | Type | Description |
|---|---|---|
CONF |
Object |
The configuration. |
Emitted each time the configuration files are read, at start and on reload.
ON('configure', function(conf) {
console.log('Name:', conf.name);
});
event
ON('update', function(err))
UPDATE() has finished.
ON('update', function(err))| Parameter | Type | Description |
|---|---|---|
err |
ErrorBuilder |
The errors, or null. |
Emitted when the update scripts of UPDATE() have run, with the errors if any.
ON('update', function(err) {
err && console.log('Update failed', err);
});
event
ON('clear', function(type, [value]))
An internal cache was cleared.
ON('clear', function(type, [value]))| Parameter | Type | Description |
|---|---|---|
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.
ON('clear', function(type) {
console.log('Cleared', type);
});
event
ON('cache_set', function(key, value, expire, sync))
A value was stored with CACHE.
ON('cache_set', function(key, value, expire, sync))| Parameter | Type | Description |
|---|---|---|
key |
String |
The key. |
value |
Object |
The value. |
expire |
Date |
The expiration. |
sync |
Boolean |
An internal flag for synchronised caches. |
Emitted by CACHE.set().
ON('cache_set', function(key) {
console.log('Cached', key);
});
event
ON('cache_expired', function(key, value))
A CACHE value expired.
ON('cache_expired', function(key, value))| Parameter | Type | Description |
|---|---|---|
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.
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.
ON('controller_render_meta', function(controller))| Parameter | Type | Description |
|---|---|---|
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.
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.
ON('websocket', function(req, socket, head))| Parameter | Type | Description |
|---|---|---|
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.
ON('websocket', function(req) {
console.log('WebSocket from', req.ip);
});
event
ON('websocket_begin', function(controller, client))
A WebSocket client connected.
ON('websocket_begin', function(controller, client))| Parameter | Type | Description |
|---|---|---|
controller |
WebSocket |
The WebSocket controller. |
client |
WebSocketClient |
The client. |
Emitted when a client is added to its WebSocket controller, before its open event.
ON('websocket_begin', function(controller, client) {
console.log('Online:', controller.online);
});
event
ON('websocket_end', function(controller, client))
A WebSocket client disconnected.
ON('websocket_end', function(controller, client))| Parameter | Type | Description |
|---|---|---|
controller |
WebSocket |
The WebSocket controller. |
client |
WebSocketClient |
The client. |
Emitted when a client is removed from its WebSocket controller.
ON('websocket_end', function(controller, client) {
console.log('Left:', client.id);
});
event
ON('componentator', function(meta))
COMPONENTATOR() is about to download components.
ON('componentator', function(meta))| Parameter | Type | Description |
|---|---|---|
meta |
Object |
{ name, components }. |
meta holds name and components from the COMPONENTATOR() call.
ON('componentator', function(meta) {
console.log('Components', meta.name);
});
event
ON('mail', function(message))
An email message is being sent.
ON('mail', function(message))| Parameter | Type | Description |
|---|---|---|
message |
MailMessage |
The message. |
Emitted for each message as the SMTP sender writes it.
ON('mail', function(message) {
console.log('Mail:', message.subject);
});
event
ON('message', function(msg, handle))
The process received an IPC message.
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 the process gets from its parent (process.on('message')), after the framework has handled its own.
ON('message', function(msg) {
if (msg.type === 'reload')
console.log('Reload requested');
});
event
ON('watcher', function(app))
The watcher (re)started the application.
ON('watcher', function(app))| Parameter | Type | Description |
|---|---|---|
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.
ON('watcher', function(app) {
app && console.log('App PID', app.pid);
});
event
ON('debug_start', function())
The application started in debug mode.
ON('debug_start', function())Emitted in the application process when it starts the first time in debug mode.
ON('debug_start', function() {
console.log('Debug start');
});
event
ON('debug_restart', function())
The application restarted in debug mode.
ON('debug_restart', function())Emitted instead of debug_start when the debug watcher restarts the application after a change.
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.
CLEANUP(stream, [callback])| Parameter | Type | Description |
|---|---|---|
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.
var stream = F.Fs.createReadStream(PATH.databases('export.csv'));
stream.pipe(F.Fs.createWriteStream(PATH.temp('export.csv')));
CLEANUP(stream, function() {
console.log('Done');
});
async function copy(stream) {
await CLEANUP(stream);
console.log('Closed');
}