node-resque

Node.js Background jobs backed by redis.

README

node-resque: The best background jobs in node.


Distributed delayed jobs in nodejs. Resque is a background job system backed by Redis (version 2.6.0 and up required). It includes priority queues, plugins, locking, delayed jobs, and more! This project is a very opinionated but API-compatible with Resque and Sidekiq (caveats). We also implement some of the popular Resque plugins, including resque-scheduler and resque-retry

The full API documentation for this package is automatically generated from the main via typedoc branch and published to https://node-resque.actionherojs.com/
Nodei stats

Test

The Resque Factory (How It Works)


Overview


Resque is a queue based task processing system that can be thought of as a "Kanban" style factory. Workers in this factory can each only work one Job at a time. They pull Jobs from Queues and work them to completion (or failure). Each Job has two parts: instructions on how to complete the job (the perform function), and any inputs necessary to complete the Job.

Queues


In our factory example, Queues are analogous to conveyor belts. Jobs are placed on the belts (Queues) and are held in order waiting for a Worker to pick them up. There are three types of Queues: regular work Queues, Delayed Job Queues, and the Failed Job Queue. The Delayed Job Queues contains Job definitions that are intended to be worked at or in a specified time. The Failed Job Queue is where Workers place any Jobs that have failed during execution.

Workers


Our Workers are the heart of the factory. Each Worker is assigned one or more Queues to check for work. After taking a Job from a Queue the Worker attempts to complete the Job. If successful, they go back to check out more work from the Queues. However, if there is a failure, the Worker records the job and its inputs in the Failed Jobs Queue before going back for more work.

Scheduler


The Scheduler can be thought of as a specialized type of Worker. Unlike other Workers, the Scheduler does not execute any Jobs, instead it manages the Delayed Job Queue. As Job definitions are added to the Delayed Job Queue they must specify when they can become available for execution. The Scheduler constantly checks to see if any Delayed Jobs are ready to execute. When a Delayed Job becomes ready for execution the Scheduler places a new instance of that Job in its defined Queue.

API Docs


You can read the API docs for Node Resque @ node-resque.actionherojs.com. These are generated automatically from the master branch via TypeDoc

Version Notes


- The version of redis required is >= 2.6.0 as we use lua scripting to create custom atomic operations
- ‼️ Version 6+ of Node Resque uses TypeScript. We will still include JavaScript transpiled code in NPM releases, but they will be generated from the TypeScript source. Functionality between node-resque v5 and v6 should be the same.
- ‼️ Version 5+ of Node Resque uses async/await. There is no upgrade path from previous versions. Node v8.0.0+ is required.

Usage


I learn best by examples:

  1. ``` js
  2. import { Worker, Plugins, Scheduler, Queue } from "node-resque";

  3. async function boot() {
  4.   // ////////////////////////
  5.   // SET UP THE CONNECTION //
  6.   // ////////////////////////

  7.   const connectionDetails = {
  8.     pkg: "ioredis",
  9.     host: "127.0.0.1",
  10.     password: null,
  11.     port: 6379,
  12.     database: 0,
  13.     // namespace: 'resque',
  14.     // looping: true,
  15.     // options: {password: 'abc'},
  16.   };

  17.   // ///////////////////////////
  18.   // DEFINE YOUR WORKER TASKS //
  19.   // ///////////////////////////

  20.   let jobsToComplete = 0;

  21.   const jobs = {
  22.     add: {
  23.       plugins: [Plugins.JobLock],
  24.       pluginOptions: {
  25.         JobLock: { reEnqueue: true },
  26.       },
  27.       perform: async (a, b) => {
  28.         await new Promise((resolve) => {
  29.           setTimeout(resolve, 1000);
  30.         });
  31.         jobsToComplete--;
  32.         tryShutdown();

  33.         const answer = a + b;
  34.         return answer;
  35.       },
  36.     },
  37.     subtract: {
  38.       perform: (a, b) => {
  39.         jobsToComplete--;
  40.         tryShutdown();

  41.         const answer = a - b;
  42.         return answer;
  43.       },
  44.     },
  45.   };

  46.   // just a helper for this demo
  47.   async function tryShutdown() {
  48.     if (jobsToComplete === 0) {
  49.       await new Promise((resolve) => {
  50.         setTimeout(resolve, 500);
  51.       });
  52.       await scheduler.end();
  53.       await worker.end();
  54.       process.exit();
  55.     }
  56.   }

  57.   // /////////////////
  58.   // START A WORKER //
  59.   // /////////////////

  60.   const worker = new Worker(
  61.     { connection: connectionDetails, queues: ["math", "otherQueue"] },
  62.     jobs
  63.   );
  64.   await worker.connect();
  65.   worker.start();

  66.   // ////////////////////
  67.   // START A SCHEDULER //
  68.   // ////////////////////

  69.   const scheduler = new Scheduler({ connection: connectionDetails });
  70.   await scheduler.connect();
  71.   scheduler.start();

  72.   // //////////////////////
  73.   // REGISTER FOR EVENTS //
  74.   // //////////////////////

  75.   worker.on("start", () => {
  76.     console.log("worker started");
  77.   });
  78.   worker.on("end", () => {
  79.     console.log("worker ended");
  80.   });
  81.   worker.on("cleaning_worker", (worker, pid) => {
  82.     console.log(`cleaning old worker ${worker}`);
  83.   });
  84.   worker.on("poll", (queue) => {
  85.     console.log(`worker polling ${queue}`);
  86.   });
  87.   worker.on("ping", (time) => {
  88.     console.log(`worker check in @ ${time}`);
  89.   });
  90.   worker.on("job", (queue, job) => {
  91.     console.log(`working job ${queue} ${JSON.stringify(job)}`);
  92.   });
  93.   worker.on("reEnqueue", (queue, job, plugin) => {
  94.     console.log(`reEnqueue job (${plugin}) ${queue} ${JSON.stringify(job)}`);
  95.   });
  96.   worker.on("success", (queue, job, result, duration) => {
  97.     console.log(
  98.       `job success ${queue} ${JSON.stringify(job)} >> ${result} (${duration}ms)`
  99.     );
  100.   });
  101.   worker.on("failure", (queue, job, failure, duration) => {
  102.     console.log(
  103.       `job failure ${queue} ${JSON.stringify(
  104.         job
  105.       )} >> ${failure} (${duration}ms)`
  106.     );
  107.   });
  108.   worker.on("error", (error, queue, job) => {
  109.     console.log(`error ${queue} ${JSON.stringify(job)}  >> ${error}`);
  110.   });
  111.   worker.on("pause", () => {
  112.     console.log("worker paused");
  113.   });

  114.   scheduler.on("start", () => {
  115.     console.log("scheduler started");
  116.   });
  117.   scheduler.on("end", () => {
  118.     console.log("scheduler ended");
  119.   });
  120.   scheduler.on("poll", () => {
  121.     console.log("scheduler polling");
  122.   });
  123.   scheduler.on("leader", () => {
  124.     console.log("scheduler became leader");
  125.   });
  126.   scheduler.on("error", (error) => {
  127.     console.log(`scheduler error >> ${error}`);
  128.   });
  129.   scheduler.on("cleanStuckWorker", (workerName, errorPayload, delta) => {
  130.     console.log(
  131.       `failing ${workerName} (stuck for ${delta}s) and failing job ${errorPayload}`
  132.     );
  133.   });
  134.   scheduler.on("workingTimestamp", (timestamp) => {
  135.     console.log(`scheduler working timestamp ${timestamp}`);
  136.   });
  137.   scheduler.on("transferredJob", (timestamp, job) => {
  138.     console.log(`scheduler enquing job ${timestamp} >> ${JSON.stringify(job)}`);
  139.   });

  140.   // //////////////////////
  141.   // CONNECT TO A QUEUE //
  142.   // //////////////////////

  143.   const queue = new Queue({ connection: connectionDetails }, jobs);
  144.   queue.on("error", function (error) {
  145.     console.log(error);
  146.   });
  147.   await queue.connect();
  148.   await queue.enqueue("math", "add", [1, 2]);
  149.   await queue.enqueue("math", "add", [1, 2]);
  150.   await queue.enqueue("math", "add", [2, 3]);
  151.   await queue.enqueueIn(3000, "math", "subtract", [2, 1]);
  152.   jobsToComplete = 4;
  153. }

  154. boot();

  155. // and when you are done
  156. // await queue.end()
  157. // await scheduler.end()
  158. // await worker.end()
  159. ```

Node Resque Interfaces: Queue, Worker, and Scheduler


There are 3 main classes in node-resque: Queue, Worker, and Scheduler

- Queue: This is the interface your program uses to interact with resque's queues - to insert jobs, check on the performance of things, and generally administer your background jobs.
- Worker: This interface is how jobs get processed. Workers are started and then they check for jobs enqueued into various queues and complete them. If there's an error, they write to the error queue.
  - There's a special class called multiWorker in Node Resque which will run many workers at once for you (see below).
- Scheduler: The scheduler can be thought of as the coordinator for Node Resque. It is primarily in charge of checking when jobs told to run later (with queue.enqueueIn or queue.enqueueAt) should be processed, but it performs some other jobs like checking for 'stuck' workers and general cluster cleanup.
  - You can (and should) run many instances of the scheduler class at once, but only one will be elected to be the 'leader', and actually do work.
  - The 'delay' defined on a scheduled job does not specify when the job should be run, but rather when the job should be enqueued. This means that node-resque can not guarantee when a job is going to be executed, only when it will become _available_ for execution (added to a Queue).

Configuration Options:


- new queue requires only the "queue" variable to be set. If you intend to run plugins withbeforeEnqueue or afterEnqueue hooks, you should also pass the jobs object to it.
- new worker has some additional options:

  1. ``` js
  2. options = {
  3.   looping: true,
  4.   timeout: 5000,
  5.   queues: "*",
  6.   name: os.hostname() + ":" + process.pid,
  7. };
  8. ```

Note that when using "*" queue:

- there's minor performance impact for checking the queues
- queues are processed in undefined order

The configuration hash passed to new NodeResque.Worker, new NodeResque.Scheduler or new NodeResque.Queue can also take a connection option.

  1. ``` js
  2. const connectionDetails = {
  3.   pkg: "ioredis",
  4.   host: "127.0.0.1",
  5.   password: "",
  6.   port: 6379,
  7.   database: 0,
  8.   namespace: "resque", // Also allow array of strings
  9. };

  10. const worker = new NodeResque.Worker(
  11.   { connection: connectionDetails, queues: "math" },
  12.   jobs
  13. );

  14. worker.on("error", (error) => {
  15.   // handler errors
  16. });

  17. await worker.connect();
  18. worker.start();

  19. // and when you are done
  20. // await worker.end()
  21. ```

You can also pass redis client directly.

  1. ``` js
  2. // assume you already initialized redis client before
  3. // the "redis" key can be IORedis.Redis or IORedis.Cluster instance

  4. const redisClient = new Redis();
  5. const connectionDetails = { redis: redisClient };

  6. // or

  7. const redisCluster = new Cluster();
  8. const connectionDetails = { redis: redisCluster };

  9. const worker = new NodeResque.Worker(
  10.   { connection: connectionDetails, queues: "math" },
  11.   jobs
  12. );

  13. worker.on("error", (error) => {
  14.   // handler errors
  15. });

  16. await worker.connect();
  17. worker.start();

  18. // and when you are done
  19. await worker.end();
  20. ```

Notes


- Be sure to call await worker.end(), await queue.end() and await scheduler.end() before shutting down your application if you want to properly clear your worker status from resque.
- When ending your application, be sure to allow your workers time to finish what they are working on
- This project implements the "scheduler" part of rescue-scheduler (the daemon which can promote enqueued delayed jobs into the work queues when it is time), but not the CRON scheduler proxy. To learn more about how to use a CRON-like scheduler, read the Job Schedules section of this document.
- "Namespace" is a string which is appended to the front of your keys in redis. Normally, it is "resque". This is helpful if you want to store multiple work queues in one redis database. Do not use keyPrefix if you are using the ioredis (default) redis driver in this project (see https://github.com/actionhero/node-resque/issues/245 for more information.)
- If you are using any plugins which effect beforeEnqueue or afterEnqueue, be sure to pass the jobs argument to the new NodeResque.Queue() constructor
- If a job fails, it will be added to a special failed queue. You can then inspect these jobs, write a plugin to manage them, move them back to the normal queues, etc. Failure behavior by default is just to enter the failed queue, but there are many options. Check out these examples from the ruby ecosystem for inspiration:
  - https://github.com/lantins/resque-retry
  - https://github.com/resque/resque/wiki/Failure-Backends
- If you plan to run more than one worker per nodejs process, be sure to name them something distinct. Names must follow the pattern hostname:pid+unique_id. For example:
- For the Retry plugin, a success message will be emitted from the worker on each attempt (even if the job fails) except the final retry. The final retry will emit a failure message instead.

If you want to learn more about running Node-Resque with docker, please view the examples here: https://github.com/actionhero/node-resque/tree/master/examples/docker

  1. ``` js
  2. const name = os.hostname() + ":" + process.pid + "+" + counter;
  3. const worker = new NodeResque.Worker(
  4.   { connection: connectionDetails, queues: "math", name: name },
  5.   jobs
  6. );
  7. ```

Worker#performInline


DO NOT USE THIS IN PRODUCTION. In tests or special cases, you may want to process/work a job in-line. To do so, you can use worker.performInline(jobName, arguments, callback). If you are planning on running a job via #performInline, this worker should also not be started, nor should be using event emitters to monitor this worker. This method will also not write to redis at all, including logging errors, modify resque's stats, etc.

Queue Management


  1. ``` js
  2. const queue = new NodeResque.Queue({ connection: connectionDetails, jobs });
  3. await queue.connect();
  4. ```

API documentation for the main methods you will be using to enqueue jobs to be worked can be found @ node-resque.actionherojs.com.

Failed Job Management


From time to time, your jobs/workers may fail. Resque workers will move failed jobs to a special failed queue which will store the original arguments of your job, the failing stack trace, and additional metadata.

error example

You can work with these failed jobs with the following methods:

let failedCount = await queue.failedCount()

- failedCount is the number of jobs in the failed queue

let failedJobs = await queue.failed(start, stop)

- failedJobs is an array listing the data of the failed jobs. Each element looks like:
`{"worker": "host:pid", "queue": "test_queue", "payload": {"class":"slowJob", "queue":"test_queue", "args":[null]}, "exception": "TypeError", "error": "MyImport is not a function", "backtrace": [' at Worker.perform (/path/to/worker:111:24)', ' at '], "failed_at": "Fri Dec 12 2014 14:01:16 GMT-0800 (PST)"}`
- To retrieve all failed jobs, use arguments: await queue.failed(0, -1)

Failing a Job


We use a try/catch pattern to catch errors in your jobs. If any job throws an
uncaught exception, it will be caught, and the job's payload moved to the error
queue for inspection.
Do not use [domain], [process.on("exit")][process.onexit], or any other method
of "catching" a process crash.

[domain]: https://nodejs.org/api/domain.html
[process.onexit]: https://nodejs.org/api/process.html#process_event_exit

The error payload looks like:

  1. ``` js
  2. { worker: 'busted-worker-3',
  3.   queue: 'busted-queue',
  4.   payload: { class: 'busted_job', queue: 'busted-queue', args: [ 1, 2, 3 ] },
  5.   exception: 'ERROR_NAME',
  6.   error: 'I broke',
  7.   failed_at: 'Sun Apr 26 2015 14:00:44 GMT+0100 (BST)' }
  8. ```

await queue.removeFailed(failedJob)

- the input failedJob is an expanded node object representing the failed job, retrieved via queue.failed

await queue.retryAndRemoveFailed(failedJob)

- the input failedJob is an expanded node object representing the failed job, retrieved via queue.failed
- this method will instantly re-enqueue a failed job back to its original queue, and delete the failed entry for that job

Failed Worker Management


Automatically


By default, the scheduler will check for workers which haven't pinged redis in 60 minutes. If this happens, we will assume the process crashed, and remove it from redis. If this worker was working on a job, we will place it in the failed queue for later inspection. Every worker has a timer running in which it then updates a key in redis every timeout (default: 5 seconds). If your job is slow, but async, there should be no problem. However, if your job consumes 100% of the CPU of the process, this timer might not fire.

To modify the 60 minute check, change stuckWorkerTimeout when configuring your scheduler, ie:

  1. ``` js
  2. const scheduler = new NodeResque.Scheduler({
  3.   stuckWorkerTimeout: (1000 * 60 * 60) // 1 hour, in ms
  4.   connection: connectionDetails
  5. })
  6. ```

Set your scheduler's stuckWorkerTimeout = false to disable this behavior.

  1. ``` js
  2. const scheduler = new NodeResque.Scheduler({
  3.   stuckWorkerTimeout: false // will not fail jobs which haven't pinged redis
  4.   connection: connectionDetails
  5. })
  6. ```

Manually


Sometimes a worker crashes is a _severe_ way, and it doesn't get the time/chance to notify redis that it is leaving the pool (this happens all the time on PAAS providers like Heroku). When this happens, you will not only need to extract the job from the now-zombie worker's "working on" status, but also remove the stuck worker. To aid you in these edge cases, await queue.cleanOldWorkers(age) is available.

Because there are no 'heartbeats' in resque, it is impossible for the application to know if a worker has been working on a long job or it is dead. You are required to provide an "age" for how long a worker has been "working", and all those older than that age will be removed, and the job they are working on moved to the error queue (where you can then use queue.retryAndRemoveFailed) to re-enqueue the job.

If you know the name of a worker that should be removed, you can also call await queue.forceCleanWorker(workerName) directly, and that will also remove the worker and move any job it was working on into the error queue. This method will still proceed for workers which are only partially in redis, indicting a previous connection failure. In this case, the job which the worker was working on is irrecoverably lost.

Job Schedules


You may want to use node-resque to schedule jobs every minute/hour/day, like a distributed CRON system. There are a number of excellent node packages to help you with this, like node-schedule and node-cron. Node-resque makes it possible for you to use the package of your choice to schedule jobs with.

Assuming you are running node-resque across multiple machines, you will need to ensure that only one of your processes is actually scheduling the jobs. To help you with this, you can inspect which of the scheduler processes is currently acting as leader, and flag only the master scheduler process to run the schedule. A full example can be found at /examples/scheduledJobs.ts, but the relevant section is:

  1. ``` js
  2. const NodeResque = require("node-resque");
  3. const schedule = require("node-schedule");
  4. const queue = new NodeResque.Queue({ connection: connectionDetails }, jobs);
  5. const scheduler = new NodeResque.Scheduler({ connection: connectionDetails });
  6. await scheduler.connect();
  7. scheduler.start();

  8. schedule.scheduleJob("10,20,30,40,50 * * * * *", async () => {
  9.   // do this job every 10 seconds, CRON style
  10.   // we want to ensure that only one instance of this job is scheduled in our environment at once,
  11.   // no matter how many schedulers we have running
  12.   if (scheduler.leader) {
  13.     console.log(">>> enqueuing a job");
  14.     await queue.enqueue("time", "ticktock", new Date().toString());
  15.   }
  16. });
  17. ```

Plugins


Just like ruby's resque, you can write worker plugins. They look like this. The 4 hooks you have are beforeEnqueue, afterEnqueue, beforePerform, and afterPerform. Plugins are classes which extend NodeResque.Plugin

  1. ``` js
  2. const { Plugin } = require("node-resque");

  3. class MyPlugin extends Plugin {
  4.   constructor(...args) {
  5.     // @ts-ignore
  6.     super(...args);
  7.     this.name = "MyPlugin";
  8.   }

  9.   beforeEnqueue() {
  10.     // console.log("** beforeEnqueue")
  11.     return true; // should the job be enqueued?
  12.   }

  13.   afterEnqueue() {
  14.     // console.log("** afterEnqueue")
  15.   }

  16.   beforePerform() {
  17.     // console.log("** beforePerform")
  18.     return true; // should the job be run?
  19.   }

  20.   afterPerform() {
  21.     // console.log("** afterPerform")
  22.   }
  23. }
  24. ```

And then your plugin can be invoked within a job like this:

  1. ``` js
  2. const jobs = {
  3.   add: {
  4.     plugins: [MyPlugin],
  5.     pluginOptions: {
  6.       MyPlugin: { thing: "stuff" },
  7.     },
  8.     perform: (a, b) => {
  9.       let answer = a + b;
  10.       return answer;
  11.     },
  12.   },
  13. };
  14. ```

notes

- You need to return true or false on the before hooks. true indicates that the action should continue, and false prevents it. This is called toRun.
- If you are writing a plugin to deal with errors which may occur during your resque job, you can inspect and modify this.worker.error in your plugin. If this.worker.error is null, no error will be logged in the resque error queue.
- There are a few included plugins, all in the src/plugins/* directory. You can write your own and include it like this:

  1. ``` js
  2. const jobs = {
  3.   add: {
  4.     plugins: [require("Myplugin").Myplugin],
  5.     pluginOptions: {
  6.       MyPlugin: { thing: "stuff" },
  7.     },
  8.     perform: (a, b) => {
  9.       let answer = a + b;
  10.       return answer;
  11.     },
  12.   },
  13. };
  14. ```

The plugins which are included with this package are:

- DelayQueueLock
  - If a job with the same name, queue, and args is already in the delayed queue(s), do not enqueue it again
- JobLock
  - If a job with the same name, queue, and args is already running, put this job back in the queue and try later
- QueueLock
  - If a job with the same name, queue, and args is already in the queue, do not enqueue it again
- Retry
  - If a job fails, retry it N times before finally placing it into the failed queue

Multi Worker


node-resque provides a wrapper around the Worker class which will auto-scale the number of resque workers. This will process more than one job at a time as long as there is idle CPU within the event loop. For example, if you have a slow job that sends email via SMTP (with low overhead), we can process many jobs at a time, but if you have a math-heavy operation, we'll stick to 1. The MultiWorker handles this by spawning more and more node-resque workers and managing the pool.

  1. ``` js
  2. const NodeResque = require("node-resque");

  3. const connectionDetails = {
  4.   pkg: "ioredis",
  5.   host: "127.0.0.1",
  6.   password: "",
  7. };

  8. const multiWorker = new NodeResque.MultiWorker(
  9.   {
  10.     connection: connectionDetails,
  11.     queues: ["slowQueue"],
  12.     minTaskProcessors: 1,
  13.     maxTaskProcessors: 100,
  14.     checkTimeout: 1000,
  15.     maxEventLoopDelay: 10,
  16.   },
  17.   jobs
  18. );

  19. // normal worker emitters
  20. multiWorker.on("start", (workerId) => {
  21.   console.log("worker[" + workerId + "] started");
  22. });
  23. multiWorker.on("end", (workerId) => {
  24.   console.log("worker[" + workerId + "] ended");
  25. });
  26. multiWorker.on("cleaning_worker", (workerId, worker, pid) => {
  27.   console.log("cleaning old worker " + worker);
  28. });
  29. multiWorker.on("poll", (workerId, queue) => {
  30.   console.log("worker[" + workerId + "] polling " + queue);
  31. });
  32. multiWorker.on("ping", (workerId, time) => {
  33.   console.log("worker[" + workerId + "] check in @ " + time);
  34. });
  35. multiWorker.on("job", (workerId, queue, job) => {
  36.   console.log(
  37.     "worker[" + workerId + "] working job " + queue + " " + JSON.stringify(job)
  38.   );
  39. });
  40. multiWorker.on("reEnqueue", (workerId, queue, job, plugin) => {
  41.   console.log(
  42.     "worker[" +
  43.       workerId +
  44.       "] reEnqueue job (" +
  45.       plugin +
  46.       ") " +
  47.       queue +
  48.       " " +
  49.       JSON.stringify(job)
  50.   );
  51. });
  52. multiWorker.on("success", (workerId, queue, job, result) => {
  53.   console.log(
  54.     "worker[" +
  55.       workerId +
  56.       "] job success " +
  57.       queue +
  58.       " " +
  59.       JSON.stringify(job) +
  60.       " >> " +
  61.       result
  62.   );
  63. });
  64. multiWorker.on("failure", (workerId, queue, job, failure) => {
  65.   console.log(
  66.     "worker[" +
  67.       workerId +
  68.       "] job failure " +
  69.       queue +
  70.       " " +
  71.       JSON.stringify(job) +
  72.       " >> " +
  73.       failure
  74.   );
  75. });
  76. multiWorker.on("error", (workerId, queue, job, error) => {
  77.   console.log(
  78.     "worker[" +
  79.       workerId +
  80.       "] error " +
  81.       queue +
  82.       " " +
  83.       JSON.stringify(job) +
  84.       " >> " +
  85.       error
  86.   );
  87. });
  88. multiWorker.on("pause", (workerId) => {
  89.   console.log("worker[" + workerId + "] paused");
  90. });
  91. multiWorker.on("multiWorkerAction", (verb, delay) => {
  92.   console.log(
  93.     "*** checked for worker status: " +
  94.       verb +
  95.       " (event loop delay: " +
  96.       delay +
  97.       "ms)"
  98.   );
  99. });

  100. multiWorker.start();
  101. ```

MultiWorker Options


The Options available for the multiWorker are:

- connection: The redis configuration options (same as worker)
- queues: Array of ordered queue names (or *) (same as worker)
- minTaskProcessors: The minimum number of workers to spawn under this multiWorker, even if there is no work to do. You need at least one, or no work will ever be processed or checked
- maxTaskProcessors: The maximum number of workers to spawn under this multiWorker, even if the queues are long and there is available CPU (the event loop isn't entirely blocked) to this node process.
- checkTimeout: How often to check if the event loop is blocked (in ms) (for adding or removing multiWorker children),
- maxEventLoopDelay: How long the event loop has to be delayed before considering it blocked (in ms),

Presentation


This package was featured heavily in this presentation I gave about background jobs + node.js. It contains more examples!

Acknowledgments


- Most of this code was inspired by / stolen from coffee-resque and coffee-resque-scheduler. Thanks!
- This Resque package aims to be fully compatible with Ruby's Resque and implementations of Resque Scheduler. Other packages from other languages may conflict.
- If you are looking for a UI to manage your Resque instances in nodejs, check out ActionHero's Resque UI