---
title: Scheduling and events
project: Total.js V4
version: 0.0.99
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v4/0-0-99/reference/scheduling-and-events/
updated: 2026-11-16T15:41:15.818Z
---

# Scheduling and events

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

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](../../guides/scheduling-and-events/) explains how to use them with examples; this page is the exact reference.

## API

### SCHEDULE(date, [repeat], fn)

Type: `method`

Registers a job that runs at a time, repeatedly, or by a cron expression.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `date` | `String|Number|Date` | yes |  | A cron expression, a date or time string, a timestamp or a Date. |
| `repeat` | `String` | no |  | A repeat period such as `'1 day'` or `'each hour'`. Not used with a cron expression. |
| `fn` | `Function` | yes |  | 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`).

Example: Every day at 03:00
```js
SCHEDULE('03:00', '1 day', function() {
	console.log('Nightly cleanup');
});
```

Example: Cron: working days at 08:00
```js
SCHEDULE('0 8 * * mo-fr', function() {
	console.log('Good morning');
});
```

Example: Once at a specific date
```js
SCHEDULE(new Date(2026, 11, 24, 8, 0), function() {
	console.log('Christmas Eve');
});
```

### schedule.id

Type: `property`

The identifier of the job.

Returns: `String`

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

### schedule.remove()

Type: `method`

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.

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

### schedule.exec()

Type: `method`

Runs the job now.

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

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

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

### ON(name, fn)

Type: `method`

Adds a listener to an event.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The event name. |
| `fn` | `Function` | yes |  | 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).

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

### ONCE(name, fn)

Type: `method`

Adds a listener that is removed after its first call.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The event name. |
| `fn` | `Function` | yes |  | The listener. |

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

Example: First request only
```js
ONCE('request', function(req) {
	console.log('First request from', req.ip);
});
```

### OFF([name], [fn])

Type: `method`

Removes event listeners.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | no |  | The event name. |
| `fn` | `Function` | no |  | 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.

Example: Remove one listener
```js
function log(req, res) {
	console.log(req.url);
}

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

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

Type: `method`

Calls all listeners of an event in the current process.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The event name. |
| `a...g` | `Object` | no |  | 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.

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

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

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

Type: `method`

Sends an event to the other processes of the application.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The event name. |
| `a...e` | `Object` | no |  | 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.

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

EMIT2('products_changed');
```

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

Type: `method`

Waits until a condition is true.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `validator` | `Function` | yes |  | Returns `true` when the wait is over. |
| `callback` | `Function` | yes |  | `function(err, success)`. |
| `timeout` | `Number` | no | `5000` | Maximum wait in milliseconds. |
| `interval` | `Number` | no | `500` | Check interval in milliseconds. |

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)`.

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

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

Type: `method`

A named timeout: each call with the same name restarts the timer.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the timer. |
| `fn` | `Function` | yes |  | `function(param)`. |
| `timeout` | `Number` | yes |  | Delay in milliseconds. |
| `limit` | `Number` | no |  | Maximum number of postponements before `fn` runs at once. |
| `param` | `Object` | no |  | 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`.

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

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

### clearTimeout2(name)

Type: `method`

Cancels a timer created by setTimeout2().

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name used in `setTimeout2()`. |

Returns: `Boolean` `true` if a timer was cancelled.

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

Example: Cancel
```js
setTimeout2('save', save, 5000);
clearTimeout2('save');
```

### PAUSESERVER(name, [enable])

Type: `method`

Pauses the server: every request gets 503 while a name is paused.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | A name for the pause. |
| `enable` | `Boolean` | no |  | `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.

Example: Pause during a migration
```js
PAUSESERVER('migration', true);
migrate(function() {
	PAUSESERVER('migration', false);
});
```

### default_interval_clear_cache : 10

Type: `config`

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'`.

### default_interval_clear_resources : 20

Type: `config`

Minutes between clean-ups of the loaded resources.

Returns: `Number`

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

### default_interval_clear_dnscache : 30

Type: `config`

Minutes between clean-ups of the DNS cache.

Returns: `Number`

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

### ON('init', function())

Type: `event`

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.

Example: Listen
```js
ON('init', function() {
	console.log('Config ready, port', CONF.port);
});
```

### ON('load', function())

Type: `event`

All application files are loaded.

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

Example: Listen
```js
ON('load', function() {
	console.log('Loaded');
});
```

### ON('ready', function())

Type: `event`

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.

Example: Listen
```js
ON('ready', function() {
	MAIN.started = NOW;
});
```

### ON('service', function(counter))

Type: `event`

Emitted every minute by the framework service.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `counter` | `Number` | yes |  | 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.

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

### ON('exit', function(signal))

Type: `event`

The application is stopping.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `signal` | `Number|String` | yes |  | 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.

Example: Listen
```js
ON('exit', function(signal) {
	console.log('Stopping with signal', signal);
});
```

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

Type: `event`

A request arrived, before routing.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `req` | `Request` | yes |  | The request. |
| `res` | `Response` | yes |  | The response. |

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

Example: Listen
```js
ON('request', function(req, res) {
	console.log(req.method, req.url);
});
```

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

Type: `event`

The request is prepared for routing.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `req` | `Request` | yes |  | The request. |
| `res` | `Response` | yes |  | The response. |

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

Example: Listen
```js
ON('request_begin', function(req) {
	req.started = Date.now();
});
```

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

Type: `event`

The response to a request has finished.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `req` | `Request` | yes |  | The request. |
| `res` | `Response` | yes |  | The response. |

Emitted when the framework has finished sending a response.

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

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

Type: `event`

A route action is about to run.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `controller` | `Controller` | yes |  | The controller of the request. |
| `name` | `String` | yes |  | The controller name. |
| `options` | `Object` | yes |  | 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.

Example: Listen
```js
ON('controller', function(controller, name) {
	controller.repository.section = name;
});
```

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

Type: `event`

A route action of one controller is about to run.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `controller` | `Controller` | yes |  | The controller of the request. |
| `name` | `String` | yes |  | The controller name. |
| `options` | `Object` | yes |  | 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`.

Example: Listen
```js
ON('@admin', function(controller) {
	controller.layout('layout_admin');
});
```

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

Type: `event`

An error response is sent, for example error404.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `req` | `Request` | yes |  | The request. |
| `res` | `Response` | yes |  | The response. |
| `exception` | `Error` | yes |  | The problem, if any. |

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

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

### ON('error', function(obj))

Type: `event`

The framework logged an error.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `obj` | `Object` | yes |  | `{ 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`.

Example: Listen
```js
ON('error', function(obj) {
	console.log(obj.name, obj.error);
});
```

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

Type: `event`

A route was registered.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `type` | `String` | yes |  | `web`, `websocket` or `file`. |
| `route` | `Object` | yes |  | The internal route object. |

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

Example: Listen
```js
ON('route', function(type) {
	console.log('A new route of type', type);
});
```

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

Type: `event`

A file of the application was installed.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `type` | `String` | yes |  | For example `'controller'` or `'model'`. |
| `name` | `String` | yes |  | The name of the file. |
| `module` | `Object` | yes |  | 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.

Example: Listen
```js
ON('install', function(type, name) {
	console.log('Installed', type, name);
});
```

### ON('configure', function(CONF))

Type: `event`

The configuration was loaded.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `CONF` | `Object` | yes |  | The configuration. |

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

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

### ON('update', function(err))

Type: `event`

UPDATE() has finished.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `err` | `ErrorBuilder` | yes |  | The errors, or `null`. |

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

Example: Listen
```js
ON('update', function(err) {
	err && console.log('Update failed', err);
});
```

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

Type: `event`

An internal cache was cleared.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `type` | `String` | yes |  | `temporary`, `resources` or `dns`. |
| `value` | `Object` | no |  | 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.

Example: Listen
```js
ON('clear', function(type) {
	console.log('Cleared', type);
});
```

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

Type: `event`

A value was stored with CACHE.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `String` | yes |  | The key. |
| `value` | `Object` | yes |  | The value. |
| `expire` | `Date` | yes |  | The expiration. |
| `sync` | `Boolean` | yes |  | An internal flag for synchronised caches. |

Emitted by `CACHE.set()`.

Example: Listen
```js
ON('cache_set', function(key) {
	console.log('Cached', key);
});
```

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

Type: `event`

A CACHE value expired.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `String` | yes |  | The key. |
| `value` | `Object` | yes |  | The expired value. |

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

Example: Listen
```js
ON('cache_expired', function(key) {
	console.log('Expired', key);
});
```

### ON('controller_render_meta', function(controller))

Type: `event`

A view is about to print its meta tags.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `controller` | `Controller` | yes |  | The controller that renders the view. |

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

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

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

Type: `event`

A WebSocket upgrade request arrived.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `req` | `Request` | yes |  | The request. |
| `socket` | `Socket` | yes |  | The network socket. |
| `head` | `Buffer` | yes |  | The first packet of the upgraded stream. |

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

Example: Listen
```js
ON('websocket', function(req) {
	console.log('WebSocket from', req.ip);
});
```

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

Type: `event`

A WebSocket client connected.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `controller` | `WebSocket` | yes |  | The WebSocket controller. |
| `client` | `WebSocketClient` | yes |  | The client. |

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

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

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

Type: `event`

A WebSocket client disconnected.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `controller` | `WebSocket` | yes |  | The WebSocket controller. |
| `client` | `WebSocketClient` | yes |  | The client. |

Emitted when a client is removed from its WebSocket controller.

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

### ON('componentator', function(meta))

Type: `event`

COMPONENTATOR() is about to download components.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `meta` | `Object` | yes |  | `{ name, components }`. |

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

Example: Listen
```js
ON('componentator', function(meta) {
	console.log('Components', meta.name);
});
```

### ON('mail', function(message))

Type: `event`

An email message is being sent.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `message` | `MailMessage` | yes |  | The message. |

Emitted for each message as the SMTP sender writes it.

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

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

Type: `event`

The process received an IPC message.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `msg` | `Object` | yes |  | The message. |
| `handle` | `Object` | yes |  | 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.

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

### ON('watcher', function(app))

Type: `event`

The watcher (re)started the application.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `app` | `ChildProcess` | yes |  | 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.

Example: Listen
```js
ON('watcher', function(app) {
	app && console.log('App PID', app.pid);
});
```

### ON('debug_start', function())

Type: `event`

The application started in debug mode.

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

Example: Listen
```js
ON('debug_start', function() {
	console.log('Debug start');
});
```

### ON('debug_restart', function())

Type: `event`

The application restarted in debug mode.

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

Example: Listen
```js
ON('debug_restart', function() {
	console.log('Restarted after a change');
});
```

### CLEANUP(stream, [callback])

Type: `method` · Since: `0.0.96`

Destroys a stream after it has finished.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `stream` | `Stream` | yes |  | A readable or writable stream. |
| `callback` | `Function` | no |  | 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.

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

CLEANUP(stream, function() {
	console.log('Done');
});
```

Example: With await
```js
async function copy(stream) {
	await CLEANUP(stream);
	console.log('Closed');
}
```
