---
title: Scheduling and events
project: Total.js V5
version: 0.0.20
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/scheduling-and-events/
updated: 2026-11-18T16:57:29.576Z
---

# Scheduling and events

> CRON(), ON(), ONCE(), OFF(), EMIT(), the built-in events, setTimeout2(), CLEANUP() and PAUSESERVER().

Global functions for scheduled and event-driven code: `CRON()` runs functions on a cron line, `ON()`, `ONCE()`, `OFF()` and `EMIT()` work with global events, and the framework emits its own events such as `ready`, `service`, `exit` and `error`. `setTimeout2()` and `clearTimeout2()` give named debounced timers, `CLEANUP()` waits for a stream and `PAUSESERVER()` holds incoming traffic.

The guide [Scheduling and events](../../guides/scheduling-and-events/) explains how they work together.

## API

### CRON(line, fn)

Type: `method`

Runs a function when the date matches a cron line.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `line` | `String` | yes |  | The cron line, e.g. `0 3 * * *`. |
| `fn` | `Function` | yes |  | `function(date)`, called when the line matches. |

Returns: `Object` The cron, with `check(date)`, `exec(date)` and `remove()`.

The line has five fields: minute, hour, day of the month, month and day of the week (`0`–`6`, or `su`, `mo`, `tu`, `we`, `th`, `fr`, `sa`). Each field is `*`, a number, a list (`1,15`), a range (`8-17`) or a step: `*/15` matches every 15th value from the first value of the field (minutes `0`, `15`, `30`, `45`; days of the month `1`, `16`, `31`) and `5/20` every 20th value from `5` (`5`, `25`, `45`). The crons are checked once a minute by the service timer and `fn` gets the current date (`NOW`). Hours and days follow the time zone of the process (`$timezone`, default `utc`).

Example: Every day at 03:00
```js
CRON('0 3 * * *', function(date) {
	NOSQL('logs').remove().where('date', '<', date.add('-30 days'));
});
```

Example: Working days
```js
CRON('30 8 * * mo-fr', function() {
	MAIL(CONF.mail_report, 'Daily report', 'mail/report', {});
});
```

Example: Every 15 minutes
```js
CRON('*/15 * * * *', function() {
	// at minutes 0, 15, 30 and 45
});
```

### cron.remove()

Type: `method`

Stops a cron.

Removes the cron returned by `CRON()` from `F.crons`, so it does not run any more.

Example: Run once
```js
var cron = CRON('0 12 * * *', function() {
	sendreport();
	cron.remove();
});
```

### F.crons

Type: `property`

The registered crons.

Returns: `Array`

An array of the objects returned by `CRON()`, in the order they were registered. Each has `check(date)` (returns `true` when the line matches), `exec(date)` (your function) and `remove()`.

Example: Count
```js
console.log(F.crons.length + ' crons');
```

### ON(name, fn)

Type: `method`

Adds a listener of a global event.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the event, or several names joined with `+`. |
| `fn` | `Function` | yes |  | The listener; it gets the arguments of `EMIT()`. |

Join several names with `+` to add the same listener to each of them. A listener of `ready` added after the application is loaded is called at once. Inside the listener `this` is `F`. `F.on()` is the same method.

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

Example: Several events
```js
ON('ready + service', function() {
	refreshcache();
});
```

### ONCE(name, fn)

Type: `method`

Adds a listener that runs only once.

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

The listener is removed after the first emission of the event. Names joined with `+` work as in `ON()`, and a `ready` listener added after the load runs at once. `F.once()` is the same method.

Example: First minute
```js
ONCE('service', function() {
	console.log('The first minute has passed');
});
```

### OFF(name, [fn])

Type: `method`

Removes a listener of a global event.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the event. |
| `fn` | `Function` | no |  | The listener to remove. |

With `fn`, removes that listener; it must be the same function that was passed to `ON()`. Without `fn`, removes all listeners of the event, including listeners of the framework. `F.off()` is the same method.

Example: Remove a listener
```js
function onservice(counter) {
	if (counter === 60)
		OFF('service', onservice);
}

ON('service', onservice);
```

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

Type: `method`

Emits a global event.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the event. |
| `a...g` | `Object` | no |  | Up to seven arguments for the listeners. |

Calls all listeners of `name` in the order they were added, synchronously, with up to seven arguments. Listeners added with `ONCE()` are removed afterwards. `F.emit()` is the same method.

Example: Emit
```js
EMIT('order.created', { id: 123, email: 'buyer@example.com' });
```

### setTimeout2(id, callback, timeout, [limit])

Type: `method`

A named timer that restarts on every call (a debounce).

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `id` | `String` | yes |  | The name of the timer. |
| `callback` | `Function` | yes |  | The function to run. |
| `timeout` | `Number` | yes |  | The delay in milliseconds. |
| `limit` | `Number` | no | `0` | How many times the timer can be postponed before a call runs the callback at once. `0` means no limit. |

If a timer with the same `id` is waiting, it is canceled and a new timer starts with the new `callback`. The callback runs only after `timeout` milliseconds without a new call with that `id`.

With `limit`, the timer can be postponed only `limit` times: the next call cancels the timer and runs its callback at once, and the counting starts again. Use it when the callback must run from time to time even while the calls do not stop.

Example: Save once after changes
```js
function changed(doc) {
	setTimeout2('save' + doc.id, function() {
		NOSQL('docs').modify(doc).where('id', doc.id);
	}, 2000);
}
```

Example: With a limit
```js
function onkey(text) {
	// searches after a pause of 300 ms, or at once when the timer has been postponed 10 times
	setTimeout2('search', function() {
		search(text);
	}, 300, 10);
}
```

### clearTimeout2(id)

Type: `method`

Cancels a named timer of setTimeout2().

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `id` | `String` | yes |  | The name of the timer. |

Returns: `Boolean` `true` when a timer was waiting.

The callback of the timer does not run.

Example: Cancel
```js
if (clearTimeout2('save' + doc.id))
	console.log('The pending save was canceled');
```

### CLEANUP(stream, [callback])

Type: `method`

Calls a function when a stream is done and destroys the stream.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `stream` | `Stream` | yes |  | A readable or writable stream. |
| `callback` | `Function` | no |  | Called when the stream is done. |

Returns: `Promise` Without a callback.

The callback runs once, on the first of `end`, `finish`, `close`, `aborted` or `error` (for a response, also when its socket closes or fails). The stream is destroyed and its open file descriptor closed at that moment. Without a callback, returns a promise. `F.cleanup()` is the same method.

Example: Wait for a file
```js
var writer = F.Fs.createWriteStream(PATH.temp('export.csv'));
writer.end('id;name\n');
CLEANUP(writer, function() {
	console.log('Written');
});
```

Example: With await
```js
await CLEANUP(writer);
```

### PAUSESERVER(name, [enable])

Type: `method`

Pauses all incoming traffic under a name.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | A name of the reason, shown on the page. |
| `enable` | `Boolean` | no |  | `true` to pause, `false` to resume; toggles when omitted. |

Returns: `Boolean` `true` when the name is paused after the call.

While at least one name is paused, every HTTP request gets the status `503`: browsers see a "Please wait" page with the paused names that reloads itself after 10 seconds, XHR requests get an error response, and new WebSocket connections are closed. `enable` `true` adds the name, `false` removes it; without `enable` the name is toggled. `F.pauseserver()` is the same method.

Example: During a migration
```js
PAUSESERVER('Database migration', true);

migrate(function() {
	PAUSESERVER('Database migration', false);
});
```

### F.paused

Type: `property`

The names paused with PAUSESERVER().

Returns: `Array`

An array of strings. The server answers with `503` while it is not empty.

Example: Check
```js
if (F.paused.length)
	console.log('Paused:', F.paused.join(', '));
```

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

Type: `event`

The application is loaded.

Emitted after the configuration, modules, actions, controllers, plugins and the other parts are loaded and the service timer is started. A listener added after that moment runs at once.

Example: Start
```js
ON('ready', function() {
	console.log('Ready on port', CONF.$port);
});
```

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

Type: `event`

Emitted right after ready.

Emitted once after `ready`, when the load of the application is complete. Unlike `ready`, a listener added later is not called.

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

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

Type: `event`

Emitted once a minute by the service timer.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `counter` | `Number` | yes |  | Minutes since the start. |

Emitted after the housekeeping of the minute and after the crons have run. `counter` is the number of minutes since the start: `1`, `2`, `3`…; use `counter % n` for longer steps.

Example: Every 10 minutes
```js
ON('service', function(counter) {
	if (counter % 10 === 0)
		refresh();
});
```

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

Type: `event`

The process is stopping.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `signal` | `Number` | yes |  | The signal passed to `F.exit()`; `15` by default. |

Emitted by `F.exit()` on `SIGTERM`, `SIGINT`, the exit of the process or a `stop` message from the parent, after workers and FlowStreams are stopped. Work done in the listener must be synchronous: the process ends right after it.

Example: Last log
```js
ON('exit', function(signal) {
	console.log('Exit', signal);
});
```

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

Type: `event`

The framework logged an error.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `obj` | `Object` | yes |  | `{ error: String, name: String, url: String, date: Date }`. |

Emitted by the default `DEF.onError` for every error passed to `F.error()` and for unhandled exceptions and rejections. `obj` is `{ error, name, url, date }`, where `error` is the error as a string. The last 10 errors are also in `F.errors`.

Example: Send errors elsewhere
```js
ON('error', function(obj) {
	console.log(obj.date, obj.name, obj.error, obj.url);
});
```

### ON('request', function(ctrl) {})

Type: `event`

An HTTP request arrived.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `ctrl` | `Controller` | yes |  | The controller of the request. |

Emitted for every HTTP request before CORS and routing. Requests stopped earlier (a paused server, a blocked IP address, the request limit, a proxy) do not reach it. `ctrl` is the controller of the request. Call `ctrl.cancel()` to stop the processing and answer the request yourself.

Example: Health check
```js
ON('request', function(ctrl) {
	if (ctrl.url === '/health/') {
		ctrl.cancel();
		ctrl.text('OK');
	}
});
```

### ON('controller', function(ctrl) {})

Type: `event`

A route was found for an HTTP request.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `ctrl` | `Controller` | yes |  | The controller of the request. |

Emitted after the route is found and the body is parsed, just before the action of the route runs (also for API routes). `ctrl.route` is the route. Call `ctrl.cancel()` to stop the processing and answer the request yourself.

Example: Log routes
```js
ON('controller', function(ctrl) {
	console.log(ctrl.method, ctrl.url);
});
```

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

Type: `event`

COMPONENTATOR() is about to download components.

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

`meta` is `{ name, components }`. Change `meta.components` to change the list of components that is downloaded.

Example: Add a component
```js
ON('componentator', function(meta) {
	meta.components += ',exec';
});
```

### ON('flowstream_error', function(meta) {})

Type: `event`

A component of a FlowStream failed.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `meta` | `Object` | yes |  | `{ id, name, error, source, instanceid, componentid }`. |

Emitted for errors of FlowStream components, after the error is printed to the console. `meta` is `{ id, name, error, source, instanceid, componentid }`: the FlowStream, its name, the error, where it happened and the instance and component.

Example: Log
```js
ON('flowstream_error', function(meta) {
	console.log(meta.name, meta.componentid, meta.error);
});
```

### ON('flowstream', function(instance) {})

Type: `event` · Since: `0.0.16`

A FlowStream instance was created.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `instance` | `Object` | yes |  | The FlowStream instance. |

Emitted when a FlowStream is created, in the main process or in a worker; `instance` is the object you control the FlowStream with. See [FlowStream](../../guides/flowstream/).

Example: Log
```js
ON('flowstream', function(instance) {
	console.log('FlowStream', instance.id);
});
```

### ON('$mail', function(message) {})

Type: `event`

An e-mail is being sent.

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

Emitted for each message just before it is written to the SMTP connection. `message` is the mail message (`subject`, `body`, `email_to`, `email_from`…). See [Mail](../../guides/mail/).

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

### ON('$stats', function(stats) {})

Type: `event`

The usage statistics of the process were updated.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `stats` | `Object` | yes |  | The statistics of the process. |

Emitted 5 seconds after the application is loaded and then once a minute by the service timer, each time after the statistics of the last minute are computed. `stats` is the same object every time; read it, do not keep a reference to its values.

The main fields: `id` and `pid` (the process), `date`, `memory` (used heap in MB), `requests`, `pending`, `errors`, `timeouts`, `online` (WebSocket clients), `download` and `upload` (MB in total), `lasterror`, `lasttimeout`, `uptime` (minutes since the start), `overload` (how many hours the process was overloaded), `mode` (`debug` or `release`) and `version` (`node`, `total`, `build`, `app`). Fields ending with `m` count the last minute: `rm` requests, `fm` files, `wm` WebSocket messages, `em` external requests, `mm` e-mails, `om` opened files, `dm`/`um` downloaded/uploaded MB, `pm`/`sm` published/subscribed messages, `cm` calls, `dbrm`/`dbwm` database reads/writes.

Example: Watch memory
```js
ON('$stats', function(stats) {
	if (stats.memory > 500)
		console.log('High memory', stats.memory, 'MB');
});
```

### ON('$message', function(msg, handle) {})

Type: `event`

The process received a message from its parent.

| 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 that arrives through `process.on('message')`, after the framework handled its own messages (`total:...`, `stop`). Useful when the application runs as a child process or in a cluster.

Example: Command
```js
ON('$message', function(msg) {
	if (msg && msg.type === 'reload')
		reload();
});
```

### ON('$update', function() {})

Type: `event`

Another process of the cluster asked for an update.

Emitted when the process receives the message `total:update`. In a cluster, a process that sends `process.send('total:update')` makes the main process forward it to the other ready processes, so each of them can reload its data.

Example: Keep a cluster in sync
```js
// the process that changed the data
process.send && process.send('total:update');

// all other processes
ON('$update', function() {
	reloadsettings();
});
```
