Subscribe to our list to receive the latest updates on Node on Fire

Class: Workers

Workers

new Workers(app)

The Workers module. This module is responsible for the orchestration of worker process types. With workers you can off-load intensive tasks away from the web processes to separate worker processes.

There are two types of workers: task-based workers and continuous workers. Task-based workers listen to a work queue and consume tasks. Other processes can tasks to a work queue. Continuous workers simply start work. It's important to understand continuous workers should be able to be restarted at any point.

To create a task-based worker:

In your controllers and models, you can pass messages to task-based workers. Under the hood, the messages are posted over a message queueing system and consumed by a worker process. For example, consider the below example:

// Our User model.

function User() {
    //
}
app.model(User);

User.prototype.afterCreate = function() {
    return this.workers.MailWorker.sendWelcomeMail(this);
};

// The Mail worker.

function MailWorker() {
    //
}
app.worker(MailWorker);

MailWorker.prototype.sendWelcomeMail = function(user) {
    // now send the mail to the user...
}

The below snippet shows how to create a continuous worker. A continuous worker starts tasks in the run method.

app.worker(function MyContinuousWorker() {
    this.run = function() {
        // Start task here.
    };
});

If you want to have a time-based process running, e.g. I want this task to run every sunday at 11 am, have a look at the Scheduler module.

Parameters:
Name Type Description
app App

The app.

Methods

addWorkerConstructor(workerConstructor)

Parameters:
Name Type Description
workerConstructor Constructor

The worker constructor.

createCreateTaskMethod(methodName)

Parameters:
Name Type Description
methodName String

The name of the method.

numberOfWorkers()

Returns:

The number of workers.

setup()

Connects to the message queue, see MessageQueue.factory.

startConsumingTasks()

Deprecated:
  • Please use Workers#startWorkers instead.

stop()

This method is invoked when the process quits. Does clean up: closes the message queue's connection.

swizzleExternalMethods()

In a multi-app project, external workers are considered workers from another app.

swizzleMethods()

In the web process, swizzles all worker methods so that they are changed to the {@see Worker#publishMessage} variant. In a web process, when invoking a worker's method, a message is published to the message queue and is picked up in the worker process.

worker(workerConstructor)

Creates the worker. You can create a worker when call {@see App#worker}.

Parameters:
Name Type Description
workerConstructor Constructor

The constructor to use.

Do you have any questions or comments on this page? Start a discussion below.

comments powered by Disqus
Subscribe to our list to receive the latest updates on Node on Fire