A lightweight, robust and fast job processing queue. Carefully written for rock solid stability and atomicity.
It uses redis for persistence, so the queue is not lost if the server goes down for any reason.
Follow manast for news and updates regarding this library.
- Minimal CPU usage by poll free design.
- Robust design based on Redis.
- Delayed jobs.
- Global pause/resume.
npm install bull
Note that you need a redis version higher or equal than 2.8.11 for bull to work properly.
var Queue = require'bull';var videoQueue = Queue'video transcoding' 6379 '127.0.0.1';var audioQueue = Queue'audio transcoding' 6379 '127.0.0.1';var imageQueue = Queue'image transcoding' 6379 '127.0.0.1';videoQueueprocess// job.data contains the custom data passed when the job was created// job.jobId contains id of this job.// transcode video asynchronously and report progressjobprogress42;// call done when finisheddone;// or give a error if errordoneError'error transcoding';// If the job throws an unhandled exception it is also handled correctlythrow Error'some unexpected error';;audioQueueprocess// transcode audio asynchronously and report progressjobprogress42;// call done when finisheddone;// or give a error if errordoneError'error transcoding';// If the job throws an unhandled exception it is also handled correctlythrow Error'some unexpected error';;imageQueueprocess// transcode image asynchronously and report progressjobprogress42;// call done when finisheddone;// or give a error if errordoneError'error transcoding';// If the job throws an unhandled exception it is also handled correctlythrow Error'some unexpected error';;videoQueueaddvideo: '';audioQueueaddaudio: '';imageQueueaddimage: '';
A queue can be paused and resumed:
queuepausethen// queue is paused now;queueresumethen// queue is resumed now
A queue emits also some useful events:
queueon'completed'// Job completed!on'failed'// Job failed with reason err!on'progress'// Job progress updated!on'paused'// The queue has been pausedon'resumed'// The queue has been resumed
Queues are cheap, so if you need many of them just create new ones with different names:
var userJohn = Queue'john';var userLisa = Queue'lisa';
Queues are robust and can be run in parallel in several threads or processes without any risk of hazards or queue corruption. Check this simple example using cluster to parallelize jobs accross processes:
varQueue = require'bull'cluster = require'cluster';var numWorkers = 8;var queue = Queue"test concurrent queue" 6379 '127.0.0.1';ifclusterisMasterfor var i = 0; i < numWorkers; i++clusterfork;clusteron'online'// Lets create a few jobs for the queue workersforvar i=0; i<500; i++queueaddfoo: 'bar';;;clusteron'exit'console.log'worker ' + workerprocesspid + ' died';;elsequeueprocessconsole.log"Job done by worker" clusterworkerid jobjobId;jobDone;;
Bull can also be used for persistent messsage queues. This is a quite useful feature in some usecases. For example, you can have two servers that need to communicate with each other. By using a queue the servers do not need to be online at the same time, this create a very robust communication channel. You can treat add as send and process as receive:
var Queue = require'bull';var sendQueue = Queue"Server B";var receiveQueue = Queue"Server A";receiveQueueprocessconsole.log"Received message" msg;done;;sendQueueaddmsg:"Hello";
var Queue = require'bull';var sendQueue = Queue"Server A";var receiveQueue = Queue"Server B";receiveQueueprocessconsole.log"Received message" msg;done;;sendQueueaddmsg:"World";
####Returning job completions
A common pattern is where you have a cluster of queue processors that just process jobs as fast as they can, and some other services that need to take the result of this processors and do something with it, maybe storing results in a database.
The most robust and scalable way to accomplish this is by combining the standard job queue with the message queue pattern: a service sends jobs to the cluster just by opening a job queue and adding jobs to it, the cluster will start processing as fast as it can. Everytime a job gets completed in the cluster a message is send to a results message queue with the result data, this queue is listened by some other service that stores the results in a database.
This is the Queue constructor. It creates a new Queue that is persisted in Redis. Everytime the same queue is instantiated it tries to process all the old jobs that may exist from a previous unfinished session.
queueName String A unique name for this QueueredisPort Number A port where redis server is runningredisHost String A host specified as IP or domain where redis is runningredisOptions Object Options to pass to the redis client https://github.com/mranney/node_redis
Defines a processing function for the jobs placed into a given Queue.
The callback is called everytime a job is placed in the queue and provides an instance of the job and a done callback to be called after the job has been completed. If done can be called providing an Error instance to signal that the job did not complete successfully.
You can specify a concurrency. Bull will then call you handler in parallel respecting this max number.
job String The job to processdone Function The done callback to be called after the job has been completed
Creates a new job and adds it to the queue. If the queue is empty the job will be executed directly, otherwise it will be placed in the queue and executed as soon as possible.
data PlainObject A plain object with arguments that will be passedto the job processing function in jobdataopts PlainObject A plain object with arguments that will be passedto the job processing function in joboptsoptsdelay Number An amount of miliseconds to wait until this jobcan be processed Note that for accurate delays both server and clientsshould have their clocks synchronizedoptslifo Boolean A boolean which if true adds the job to the rightof the queue instead of the left default falseoptstimeout Number The number of milliseconds after which the jobshould be fail with a timeout error optionalreturns Promise A promise that resolves when the job has been succesfullyadded to the queue or rejects if some error occured
Returns a promise that resolves when the queue is paused. The pause is global, meaning that all workers in all queue instances for a given queue will be paused. A paused queue will not process new jobs until resumed, but current jobs being processed will continue until they are finalized.
Pausing a queue that is already paused does nothing.
returns Promise A promise that resolves when the queue is paused
Returns a promise that resolves when the queue is resumed after being paused. The resume is global, meaning that all workers in all queue instances for a given queue will be resumed.
Resuming a queue that is not paused does nothing.
returns Promise A promise that resolves when the queue is resumed
Returns a promise that returns the number of jobs in the queue, waiting or paused. Since there may be other processes adding or processing jobs, this value may be true only for a very small amount of time.
returns Promise A promise that resolves with the current jobs count
Empties a queue deleting all the input lists and associated jobs.
returns Promise A promise that resolves with the queue is emptied
Returns a promise that will return the job instance associated with the
parameter. If the specified job cannot be located, the promise callback parameter
will be set to
jobId String A string identifying the ID of the to look upreturns Promise A promise that resolves with the job instance when the jobhas been retrieved to the queue or null otherwise
This is the Queue constructor of priority queue. It works same a normal queue, with same function and parameters. The only difference is that the Queue#add() allow an options opts.priority that could take ["low", "normal", "medium", "hight", "critical"]. If no options provider, "normal" will be taken.
The priority queue will process more often highter priority jobs than lower.
var PriorityQueue = require"bull/lib/priority-queue";var queue = "myPriorityQueues";queueaddtodo: "Improve feature" priority: "normal";queueaddtodo: "Read 9gags" priority: "low";queueaddtodo: "Fix my test unit" priority: "critical";queueprocessconsole.log"I have to: " + jobdatatodo;done;;
Warning: Priority queue use 5 times more redis connections than a normal queue.
A job includes all data needed to perform its execution, as well as the progress method needed to update its progress.
The most important property for the user is Job##data that includes the object that was passed to Queue##add, and that is normally used to perform the job.
Removes a Job from the queue from all the lists where it may be included.
returns Promise A promise that resolves when the job is removed
(The MIT License)
Copyright (c) 2013 Manuel Astudillo email@example.com
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.