1 | # Kue
|
2 |
|
3 | [![Build Status](https://travis-ci.org/LearnBoost/kue.svg?branch=master)](https://travis-ci.org/LearnBoost/kue.svg?branch=master&style=flat)
|
4 | [![Dependency Status](https://img.shields.io/david/learnboost/kue.svg?style=flat)](https://david-dm.org/learnboost/kue)
|
5 | [![npm version](https://badge.fury.io/js/kue.svg?style=flat)](http://badge.fury.io/js/kue)
|
6 | [![Stories in Ready](https://badge.waffle.io/learnboost/kue.svg?style=flat&label=ready&title=Ready)](https://waffle.io/learnboost/kue)
|
7 |
|
8 | Kue is a priority job queue backed by [redis](http://redis.io), built for [node.js](http://nodejs.org).
|
9 |
|
10 | **PROTIP** This is the latest Kue documentation, make sure to also read the [changelist](History.md).
|
11 |
|
12 | ## Installation
|
13 |
|
14 | $ npm install kue
|
15 |
|
16 | [![NPM](https://nodei.co/npm/kue.png?downloads=true&stars=true)](https://nodei.co/npm/kue/)
|
17 |
|
18 | ## Features
|
19 |
|
20 | - Delayed jobs
|
21 | - Distribution of parallel work load
|
22 | - Job event and progress pubsub
|
23 | - Rich integrated UI
|
24 | - Infinite scrolling
|
25 | - UI progress indication
|
26 | - Job specific logging
|
27 | - Powered by Redis
|
28 | - Optional retries with backoff
|
29 | - Full-text search capabilities
|
30 | - RESTful JSON API
|
31 | - Graceful workers shutdown
|
32 |
|
33 | ## Overview
|
34 |
|
35 | - [Creating Jobs](#creating-jobs)
|
36 | - [Jobs Priority](#job-priority)
|
37 | - [Failure Attempts](#failure-attempts)
|
38 | - [Failure Backoff](#failure-backoff)
|
39 | - [Job Logs](#job-logs)
|
40 | - [Job Progress](#job-progress)
|
41 | - [Job Events](#job-events)
|
42 | - [Queue Events](#queue-events)
|
43 | - [Delayed Jobs](#delayed-jobs)
|
44 | - [Processing Jobs](#processing-jobs)
|
45 | - [Processing Concurrency](#processing-concurrency)
|
46 | - [Pause Processing](#pause-processing)
|
47 | - [Updating Progress](#updating-progress)
|
48 | - [Graceful Shutdown](#graceful-shutdown)
|
49 | - [Error Handling](#error-handling)
|
50 | - [Queue Maintenance](#queue-maintenance)
|
51 | - [Redis Connection Settings](#redis-connection-settings)
|
52 | - [User-Interface](#user-interface)
|
53 | - [JSON API](#json-api)
|
54 | - [Parallel Processing With Cluster](#parallel-processing-with-cluster)
|
55 | - [Securing Kue](#securing-kue)
|
56 | - [Screencasts](#screencasts)
|
57 | - [License](#license)
|
58 |
|
59 |
|
60 |
|
61 | ## Creating Jobs
|
62 |
|
63 | First create a job `Queue` with `kue.createQueue()`:
|
64 |
|
65 | ```js
|
66 | var kue = require('kue')
|
67 | , queue = kue.createQueue();
|
68 | ```
|
69 |
|
70 | Calling `queue.create()` with the type of job ("email"), and arbitrary job data will return a `Job`, which can then be `save()`ed, adding it to redis, with a default priority level of "normal". The `save()` method optionally accepts a callback, responding with an `error` if something goes wrong. The `title` key is special-cased, and will display in the job listings within the UI, making it easier to find a specific job.
|
71 |
|
72 | ```js
|
73 | var job = queue.create('email', {
|
74 | title: 'welcome email for tj'
|
75 | , to: 'tj@learnboost.com'
|
76 | , template: 'welcome-email'
|
77 | }).save( function(err){
|
78 | if( !err ) console.log( job.id );
|
79 | });
|
80 | ```
|
81 |
|
82 | ### Job Priority
|
83 |
|
84 | To specify the priority of a job, simply invoke the `priority()` method with a number, or priority name, which is mapped to a number.
|
85 |
|
86 | ```js
|
87 | queue.create('email', {
|
88 | title: 'welcome email for tj'
|
89 | , to: 'tj@learnboost.com'
|
90 | , template: 'welcome-email'
|
91 | }).priority('high').save();
|
92 | ```
|
93 |
|
94 | The default priority map is as follows:
|
95 |
|
96 | ```js
|
97 | {
|
98 | low: 10
|
99 | , normal: 0
|
100 | , medium: -5
|
101 | , high: -10
|
102 | , critical: -15
|
103 | };
|
104 | ```
|
105 |
|
106 | ### Failure Attempts
|
107 |
|
108 | By default jobs only have _one_ attempt, that is when they fail, they are marked as a failure, and remain that way until you intervene. However, Kue allows you to specify this, which is important for jobs such as transferring an email, which upon failure, may usually retry without issue. To do this invoke the `.attempts()` method with a number.
|
109 |
|
110 | ```js
|
111 | queue.create('email', {
|
112 | title: 'welcome email for tj'
|
113 | , to: 'tj@learnboost.com'
|
114 | , template: 'welcome-email'
|
115 | }).priority('high').attempts(5).save();
|
116 | ```
|
117 |
|
118 | ### Failure Backoff
|
119 | Job retry attempts are done as soon as they fail, with no delay, even if your job had a delay set via `Job#delay`. If you want to delay job re-attempts upon failures (known as backoff) you can use `Job#backoff` method in different ways:
|
120 |
|
121 | ```js
|
122 | // Honor job's original delay (if set) at each attempt, defaults to fixed backoff
|
123 | job.attempts(3).backoff( true )
|
124 |
|
125 | // Override delay value, fixed backoff
|
126 | job.attempts(3).backoff( {delay: 60*1000, type:'fixed'} )
|
127 |
|
128 | // Enable exponential backoff using original delay (if set)
|
129 | job.attempts(3).backoff( {type:'exponential'} )
|
130 |
|
131 | // Use a function to get a customized next attempt delay value
|
132 | job.attempts(3).backoff( function( attempts, delay ){
|
133 | return my_customized_calculated_delay;
|
134 | })
|
135 | ```
|
136 |
|
137 | In the last scenario, provided function will be executed (via eval) on each re-attempt to get next attempt delay value, meaning that you can't reference external/context variables within it.
|
138 |
|
139 | **Note** that backoff feature depends on `.delay` under the covers and therefore `.promote()` needs to be called if used.
|
140 |
|
141 | ### Job Logs
|
142 |
|
143 | Job-specific logs enable you to expose information to the UI at any point in the job's life-time. To do so simply invoke `job.log()`, which accepts a message string as well as variable-arguments for sprintf-like support:
|
144 |
|
145 | ```js
|
146 | job.log('$%d sent to %s', amount, user.name);
|
147 | ```
|
148 |
|
149 | ### Job Progress
|
150 |
|
151 | Job progress is extremely useful for long-running jobs such as video conversion. To update the job's progress simply invoke `job.progress(completed, total [, data])`:
|
152 |
|
153 | ```js
|
154 | job.progress(frames, totalFrames);
|
155 | ```
|
156 |
|
157 | data can be used to pass extra information about the job. For example a message or an object with some extra contextual data to the current status.
|
158 |
|
159 | ### Job Events
|
160 |
|
161 | Job-specific events are fired on the `Job` instances via Redis pubsub. The following events are currently supported:
|
162 |
|
163 | - `enqueue` the job is now queued
|
164 | - `promotion` the job is promoted from delayed state to queued
|
165 | - `progress` the job's progress ranging from 0-100
|
166 | - 'failed attempt' the job has failed, but has remaining attempts yet
|
167 | - `failed` the job has failed and has no remaining attempts
|
168 | - `complete` the job has completed
|
169 |
|
170 |
|
171 | For example this may look something like the following:
|
172 |
|
173 | ```js
|
174 | var job = queue.create('video conversion', {
|
175 | title: 'converting loki\'s to avi'
|
176 | , user: 1
|
177 | , frames: 200
|
178 | });
|
179 |
|
180 | job.on('complete', function(result){
|
181 | console.log('Job completed with data ', result);
|
182 |
|
183 | }).on('failed attempt', function(errorMessage, doneAttempts){
|
184 | console.log('Job failed');
|
185 |
|
186 | }).on('failed', function(errorMessage){
|
187 | console.log('Job failed');
|
188 |
|
189 | }).on('progress', function(progress, data){
|
190 | console.log('\r job #' + job.id + ' ' + progress + '% complete with data ', data );
|
191 |
|
192 | });
|
193 | ```
|
194 |
|
195 | **Note** that Job level events are not guaranteed to be received upon process restarts, since restarted node.js process will lose the reference to the specific Job object. If you want a more reliable event handler look for [Queue Events](#queue-events).
|
196 |
|
197 | ### Queue Events
|
198 |
|
199 | Queue-level events provide access to the job-level events previously mentioned, however scoped to the `Queue` instance to apply logic at a "global" level. An example of this is removing completed jobs:
|
200 |
|
201 | ```js
|
202 | queue.on('job enqueue', function(id, type){
|
203 | console.log( 'Job %s got queued of type %s', id, type );
|
204 |
|
205 | }).on('job complete', function(id, result){
|
206 | kue.Job.get(id, function(err, job){
|
207 | if (err) return;
|
208 | job.remove(function(err){
|
209 | if (err) throw err;
|
210 | console.log('removed completed job #%d', job.id);
|
211 | });
|
212 | });
|
213 | });
|
214 | ```
|
215 |
|
216 | The events available are the same as mentioned in "Job Events", however prefixed with "job ".
|
217 |
|
218 | ### Delayed Jobs
|
219 |
|
220 | Delayed jobs may be scheduled to be queued for an arbitrary distance in time by invoking the `.delay(ms)` method, passing the number of milliseconds relative to _now_. Alternatively, you can pass a JavaScript `Date` object with a specific time in the future.
|
221 | This automatically flags the `Job` as "delayed".
|
222 |
|
223 | ```js
|
224 | var email = queue.create('email', {
|
225 | title: 'Account renewal required'
|
226 | , to: 'tj@learnboost.com'
|
227 | , template: 'renewal-email'
|
228 | }).delay(milliseconds)
|
229 | .priority('high')
|
230 | .save();
|
231 | ```
|
232 |
|
233 | When using delayed jobs, we must also check the delayed jobs with a timer, promoting them if the scheduled delay has been exceeded. This `setInterval` is defined within `Queue#promote(ms,limit)`, defaulting to a check of top 200 jobs every 5 seconds. If you have a cluster of kue processes, you must call `.promote` in just one (preferably master) process or promotion race can happen.
|
234 |
|
235 | ```js
|
236 | queue.promote();
|
237 | ```
|
238 |
|
239 | ## Processing Jobs
|
240 |
|
241 | Processing jobs is simple with Kue. First create a `Queue` instance much like we do for creating jobs, providing us access to redis etc, then invoke `queue.process()` with the associated type.
|
242 | Note that unlike what the name `createQueue` suggests, it currently returns a singleton `Queue` instance. So you can configure and use only a single `Queue` object within your node.js process.
|
243 |
|
244 | In the following example we pass the callback `done` to `email`, When an error occurs we invoke `done(err)` to tell Kue something happened, otherwise we invoke `done()` only when the job is complete. If this function responds with an error it will be displayed in the UI and the job will be marked as a failure. The error object passed to done, should be of standard type `Error`.
|
245 |
|
246 | ```js
|
247 | var kue = require('kue')
|
248 | , queue = kue.createQueue();
|
249 |
|
250 | queue.process('email', function(job, done){
|
251 | email(job.data.to, done);
|
252 | });
|
253 |
|
254 | function email(address, done) {
|
255 | if(!isValidEmail(address)) {
|
256 | //done('invalid to address') is possible but discouraged
|
257 | return done(new Error('invalid to address'));
|
258 | }
|
259 | // email send stuff...
|
260 | done();
|
261 | }
|
262 | ```
|
263 |
|
264 | Workers can also pass job result as the second parameter to done `done(null,result)` to store that in `Job.result` key. `result` is also passed through `complete` event handlers so that job producers can receive it if they like to.
|
265 |
|
266 | ### Processing Concurrency
|
267 |
|
268 | By default a call to `queue.process()` will only accept one job at a time for processing. For small tasks like sending emails this is not ideal, so we may specify the maximum active jobs for this type by passing a number:
|
269 |
|
270 | ```js
|
271 | queue.process('email', 20, function(job, done){
|
272 | // ...
|
273 | });
|
274 | ```
|
275 |
|
276 | ### Pause Processing
|
277 |
|
278 | Workers can temporary pause and resume their activity. It is, after calling `pause` they will receive no jobs in their process callback until `resume` is called. `pause` function gracefully shutdowns this worker, and uses the same internal functionality as `shutdown` method in [Graceful Shutdown](#graceful-shutdown).
|
279 |
|
280 | ```js
|
281 | queue.process('email', function(job, done, ctx){
|
282 | ctx.pause( function(err){
|
283 | console.log("Worker is paused... ");
|
284 | setTimeout( function(){ ctx.resume(); }, 10000 );
|
285 | }, 5000);
|
286 | });
|
287 | ```
|
288 |
|
289 | ### Updating Progress
|
290 |
|
291 | For a "real" example, let's say we need to compile a PDF from numerous slides with [node-canvas](http://github.com/learnboost/node-canvas). Our job may consist of the following data, note that in general you should _not_ store large data in the job it-self, it's better to store references like ids, pulling them in while processing.
|
292 |
|
293 | ```js
|
294 | queue.create('slideshow pdf', {
|
295 | title: user.name + "'s slideshow"
|
296 | , slides: [...] // keys to data stored in redis, mongodb, or some other store
|
297 | });
|
298 | ```
|
299 |
|
300 | We can access this same arbitrary data within a separate process while processing, via the `job.data` property. In the example we render each slide one-by-one, updating the job's log and process.
|
301 |
|
302 | ```js
|
303 | queue.process('slideshow pdf', 5, function(job, done){
|
304 | var slides = job.data.slides
|
305 | , len = slides.length;
|
306 |
|
307 | function next(i) {
|
308 | var slide = slides[i]; // pretend we did a query on this slide id ;)
|
309 | job.log('rendering %dx%d slide', slide.width, slide.height);
|
310 | renderSlide(slide, function(err){
|
311 | if (err) return done(err);
|
312 | job.progress(i, len, {nextSlide : i == len ? 'itsdone' : i + 1});
|
313 | if (i == len) done()
|
314 | else next(i + 1);
|
315 | });
|
316 | }
|
317 |
|
318 | next(0);
|
319 | });
|
320 | ```
|
321 |
|
322 | ### Graceful Shutdown
|
323 |
|
324 | As of Kue 0.7.0, a `Queue#shutdown(fn, timeout)` is added which signals all workers to stop processing after their current active job is done. Workers will wait `timeout` milliseconds for their active job's done to be called or mark the active job `failed` with shutdown error reason. When all workers tell Kue they are stopped `fn` is called.
|
325 |
|
326 | ```javascript
|
327 | var queue = require('kue').createQueue();
|
328 |
|
329 | process.once( 'SIGTERM', function ( sig ) {
|
330 | queue.shutdown(function(err) {
|
331 | console.log( 'Kue is shut down.', err||'' );
|
332 | process.exit( 0 );
|
333 | }, 5000 );
|
334 | });
|
335 | ```
|
336 |
|
337 | ## Error Handling
|
338 |
|
339 | All errors either in Redis client library or Queue are emitted to the `Queue` object. You should bind to `error` events to prevent uncaught exceptions or debug kue errors.
|
340 |
|
341 | ```javascript
|
342 | var queue = require('kue').createQueue();
|
343 |
|
344 | queue.on( 'error', function( err ) {
|
345 | console.log( 'Oops... ', err );
|
346 | });
|
347 | ```
|
348 |
|
349 | ### Prevent from Stuck Active Jobs
|
350 |
|
351 | Kue marks a job complete/failed when `done` is called by your worker, so you should use proper error handling to prevent uncaught exceptions in your worker's code and node.js process exiting before in handle jobs get done.
|
352 | This can be achieved in two ways:
|
353 |
|
354 | 1. Wrapping your worker's process function in [Domains](https://nodejs.org/api/domain.html)
|
355 |
|
356 | ```js
|
357 | queue.process('my-error-prone-task', function(job, done){
|
358 | var domain = require('domain').create();
|
359 | domain.on('error', function(err){
|
360 | done(err);
|
361 | });
|
362 | domain.run(function(){ // your process function
|
363 | throw new Error( 'bad things happen' );
|
364 | done();
|
365 | });
|
366 | });
|
367 | ```
|
368 |
|
369 | This is the softest and best solution, however is not built-in with Kue. Please refer to [this discussion](https://github.com/kriskowal/q/issues/120). You can comment on this feature in the related open Kue [issue](https://github.com/LearnBoost/kue/pull/403).
|
370 |
|
371 | You can also use promises to do something like
|
372 |
|
373 | ```js
|
374 | queue.process('my-error-prone-task', function(job, done){
|
375 | Promise.method( function(){ // your process function
|
376 | throw new Error( 'bad things happen' );
|
377 | })().nodeify(done)
|
378 | });
|
379 | ```
|
380 |
|
381 | but this won't catch exceptions in your async call stack as domains do.
|
382 |
|
383 |
|
384 |
|
385 | 2. Binding to `uncaughtException` and gracefully shutting down the Kue.
|
386 |
|
387 | ```js
|
388 | process.once( 'uncaughtException', function(err){
|
389 | queue.shutdown(function(err2){
|
390 | process.exit( 0 );
|
391 | }, 2000 );
|
392 | });
|
393 | ```
|
394 |
|
395 | ### Unstable Redis connections
|
396 |
|
397 | Kue currently uses client side job state management and when redis crashes in the middle of that operations, some stuck jobs or index inconsistencies will happen. If you are facing poor redis connections or an unstable redis service you can start Kue's watchdog to fix stuck inactive jobs (if any) by calling:
|
398 |
|
399 | ```js
|
400 | queue.watchStuckJobs()
|
401 | ```
|
402 |
|
403 | Kue will be refactored to fully atomic job state management from version 1.0 and this will happen by lua scripts and/or BRPOPLPUSH combination. You can read more [here](https://github.com/LearnBoost/kue/issues/130) and [here](https://github.com/LearnBoost/kue/issues/38).
|
404 |
|
405 | ## Queue Maintenance
|
406 |
|
407 | ### Programmatic Job Management
|
408 |
|
409 | If you did none of above or your process lost active jobs in any way, you can recover from them when your process is restarted. A blind logic would be to re-queue all stuck jobs:
|
410 |
|
411 | ```js
|
412 | queue.active( function( err, ids ) {
|
413 | ids.forEach( function( id ) {
|
414 | kue.Job.get( id, function( err, job ) {
|
415 | // if job is a stuck one
|
416 | job.inactive();
|
417 | });
|
418 | });
|
419 | });
|
420 | ```
|
421 |
|
422 | **Note** *in a clustered deployment your application should be aware not to involve a job that is valid, currently inprocess by other workers.*
|
423 |
|
424 | ### Job Cleanup
|
425 |
|
426 | Jobs data and search indexes eat up redis memory space, so you will need some job-keeping process in real world deployments. Your first chance is using automatic job removal on completion.
|
427 |
|
428 | ```javascript
|
429 | queue.create( ... ).removeOnComplete( true ).save()
|
430 | ```
|
431 |
|
432 | But if you eventually/temporally need completed job data, you can setup an on-demand job removal script like below to remove top `n` completed jobs:
|
433 |
|
434 | ```js
|
435 | kue.Job.rangeByState( 'complete', 0, n, 'asc', function( err, jobs ) {
|
436 | jobs.forEach( function( job ) {
|
437 | job.remove( function(){
|
438 | console.log( 'removed ', job.id );
|
439 | });
|
440 | }
|
441 | });
|
442 | ```
|
443 |
|
444 | **Note** *that you should provide enough time for `.remove` calls on each job object to complete before your process exits, or job indexes will leak*
|
445 |
|
446 |
|
447 | ## Redis Connection Settings
|
448 |
|
449 | By default, Kue will connect to Redis using the client default settings (port defaults to `6379`, host defaults to `127.0.0.1`, prefix defaults to `q`). `Queue#createQueue(options)` accepts redis connection options in `options.redis` key.
|
450 |
|
451 | ```javascript
|
452 | var kue = require('kue');
|
453 | var q = kue.createQueue({
|
454 | prefix: 'q',
|
455 | redis: {
|
456 | port: 1234,
|
457 | host: '10.0.50.20',
|
458 | auth: 'password',
|
459 | db: 3, // if provided select a non-default redis db
|
460 | options: {
|
461 | // see https://github.com/mranney/node_redis#rediscreateclient
|
462 | }
|
463 | }
|
464 | });
|
465 | ```
|
466 |
|
467 | `prefix` controls the key names used in Redis. By default, this is simply `q`. Prefix generally shouldn't be changed unless you need to use one Redis instance for multiple apps. It can also be useful for providing an isolated testbed across your main application.
|
468 |
|
469 | You can also specify the connection information as a URL string.
|
470 |
|
471 | ```js
|
472 | var q = kue.createQueue({
|
473 | redis: 'redis://example.com:1234?redis_option=value&redis_option=value'
|
474 | });
|
475 | ```
|
476 |
|
477 | #### Connecting using Unix Domain Sockets
|
478 |
|
479 | Since [node_redis](https://github.com/mranney/node_redis) supports Unix Domain Sockets, you can also tell Kue to do so. See [unix-domain-socket](https://github.com/mranney/node_redis#unix-domain-socket) for your redis server configuration.
|
480 |
|
481 | ```javascript
|
482 | var kue = require('kue');
|
483 | var q = kue.createQueue({
|
484 | prefix: 'q',
|
485 | redis: {
|
486 | socket: '/data/sockets/redis.sock',
|
487 | auth: 'password',
|
488 | options: {
|
489 | // see https://github.com/mranney/node_redis#rediscreateclientport-host-options
|
490 | }
|
491 | }
|
492 | });
|
493 | ```
|
494 |
|
495 | #### Replacing Redis Client Module
|
496 |
|
497 | Any node.js redis client library that conforms (or when adapted) to [node_redis](https://github.com/mranney/node_redis) API can be injected into Kue. You should only provide a `createClientFactory` function as a redis connection factory instead of providing node_redis connection options.
|
498 |
|
499 | Below is a sample code to enable [redis-sentinel](https://github.com/ortoo/node-redis-sentinel) to connect to [Redis Sentinel](http://redis.io/topics/sentinel) for automatic master/slave failover.
|
500 |
|
501 | ```javascript
|
502 | var kue = require('kue');
|
503 | var Sentinel = require('redis-sentinel');
|
504 | var endpoints = [
|
505 | {host: '192.168.1.10', port: 6379},
|
506 | {host: '192.168.1.11', port: 6379}
|
507 | ];
|
508 | var opts = options || {}; // Standard node_redis client options
|
509 | var masterName = 'mymaster';
|
510 | var sentinel = Sentinel.Sentinel(endpoints);
|
511 |
|
512 | var q = kue.createQueue({
|
513 | redis: {
|
514 | createClientFactory: function(){
|
515 | return sentinel.createClient(masterName, opts);
|
516 | }
|
517 | }
|
518 | });
|
519 | ```
|
520 |
|
521 | **Note** *that all `<0.8.x` client codes should be refactored to pass redis options to `Queue#createQueue` instead of monkey patched style overriding of `redis#createClient` or they will be broken from Kue `0.8.x`.*
|
522 |
|
523 |
|
524 | ## User-Interface
|
525 |
|
526 | The UI is a small [Express](http://github.com/visionmedia/express) application, to fire it up simply run the following, altering the port etc as desired.
|
527 |
|
528 | ```js
|
529 | var kue = require('kue');
|
530 | kue.createQueue(...);
|
531 | kue.app.listen(3000);
|
532 | ```
|
533 |
|
534 | The title defaults to "Kue", to alter this invoke:
|
535 |
|
536 | ```js
|
537 | kue.app.set('title', 'My Application');
|
538 | ```
|
539 |
|
540 | **Note** *that if you are using non-default Kue options, `kue.createQueue(...)` must be called before accessing `kue.app`.*
|
541 |
|
542 | ### Third-party interfaces
|
543 |
|
544 | You can also use [Kue-UI](https://github.com/StreetHub/kue-ui) web interface contributed by [Arnaud Bénard](https://github.com/arnaudbenard)
|
545 |
|
546 |
|
547 | ## JSON API
|
548 |
|
549 | Along with the UI Kue also exposes a JSON API, which is utilized by the UI.
|
550 |
|
551 | ### GET /job/search?q=
|
552 |
|
553 | Query jobs, for example "GET /job/search?q=avi video":
|
554 |
|
555 | ```js
|
556 | ["5", "7", "10"]
|
557 | ```
|
558 |
|
559 | By default kue indexes the whole Job data object for searching, but this can be customized via calling `Job#searchKeys` to tell kue which keys on Job data to create index for:
|
560 |
|
561 | ```javascript
|
562 | var kue = require('kue');
|
563 | queue = kue.createQueue();
|
564 | queue.create('email', {
|
565 | title: 'welcome email for tj'
|
566 | , to: 'tj@learnboost.com'
|
567 | , template: 'welcome-email'
|
568 | }).searchKeys( ['to', 'title'] ).save();
|
569 | ```
|
570 |
|
571 | You may also fully disable search indexes for redis memory optimization:
|
572 |
|
573 | ```javascript
|
574 | var kue = require('kue');
|
575 | q = kue.createQueue({
|
576 | disableSearch: true
|
577 | });
|
578 | ```
|
579 |
|
580 | ### GET /stats
|
581 |
|
582 | Currently responds with state counts, and worker activity time in milliseconds:
|
583 |
|
584 | ```js
|
585 | {"inactiveCount":4,"completeCount":69,"activeCount":2,"failedCount":0,"workTime":20892}
|
586 | ```
|
587 |
|
588 | ### GET /job/:id
|
589 |
|
590 | Get a job by `:id`:
|
591 |
|
592 | ```js
|
593 | {"id":"3","type":"email","data":{"title":"welcome email for tj","to":"tj@learnboost.com","template":"welcome-email"},"priority":-10,"progress":"100","state":"complete","attempts":null,"created_at":"1309973155248","updated_at":"1309973155248","duration":"15002"}
|
594 | ```
|
595 |
|
596 | ### GET /job/:id/log
|
597 |
|
598 | Get job `:id`'s log:
|
599 |
|
600 | ```js
|
601 | ['foo', 'bar', 'baz']
|
602 | ```
|
603 |
|
604 | ### GET /jobs/:from..:to/:order?
|
605 |
|
606 | Get jobs with the specified range `:from` to `:to`, for example "/jobs/0..2", where `:order` may be "asc" or "desc":
|
607 |
|
608 | ```js
|
609 | [{"id":"12","type":"email","data":{"title":"welcome email for tj","to":"tj@learnboost.com","template":"welcome-email"},"priority":-10,"progress":0,"state":"active","attempts":null,"created_at":"1309973299293","updated_at":"1309973299293"},{"id":"130","type":"email","data":{"title":"welcome email for tj","to":"tj@learnboost.com","template":"welcome-email"},"priority":-10,"progress":0,"state":"active","attempts":null,"created_at":"1309975157291","updated_at":"1309975157291"}]
|
610 | ```
|
611 |
|
612 | ### GET /jobs/:state/:from..:to/:order?
|
613 |
|
614 | Same as above, restricting by `:state` which is one of:
|
615 |
|
616 | - active
|
617 | - inactive
|
618 | - failed
|
619 | - complete
|
620 |
|
621 | ### GET /jobs/:type/:state/:from..:to/:order?
|
622 |
|
623 | Same as above, however restricted to `:type` and `:state`.
|
624 |
|
625 | ### DELETE /job/:id
|
626 |
|
627 | Delete job `:id`:
|
628 |
|
629 | $ curl -X DELETE http://local:3000/job/2
|
630 | {"message":"job 2 removed"}
|
631 |
|
632 | ### POST /job
|
633 |
|
634 | Create a job:
|
635 |
|
636 | $ curl -H "Content-Type: application/json" -X POST -d \
|
637 | '{
|
638 | "type": "email",
|
639 | "data": {
|
640 | "title": "welcome email for tj",
|
641 | "to": "tj@learnboost.com",
|
642 | "template": "welcome-email"
|
643 | },
|
644 | "options" : {
|
645 | "attempts": 5,
|
646 | "priority": "high"
|
647 | }
|
648 | }' http://localhost:3000/job
|
649 | {"message": "job created", "id": 3}
|
650 |
|
651 | You can create multiple jobs at once by passing an array. In this case, the response will be an array too.
|
652 |
|
653 | $ curl -H "Content-Type: application/json" -X POST -d \
|
654 | '[{
|
655 | "type": "email",
|
656 | "data": {
|
657 | "title": "welcome email for tj",
|
658 | "to": "tj@learnboost.com",
|
659 | "template": "welcome-email"
|
660 | },
|
661 | "options" : {
|
662 | "attempts": 5,
|
663 | "priority": "high"
|
664 | }
|
665 | },
|
666 | {
|
667 | "type": "email",
|
668 | "data": {
|
669 | "title": "followup email for tj",
|
670 | "to": "tj@learnboost.com",
|
671 | "template": "followup-email",
|
672 | "delay": 86400
|
673 | },
|
674 | "options" : {
|
675 | "attempts": 5,
|
676 | "priority": "high"
|
677 | }
|
678 | }]' http://localhost:3000/job
|
679 | [
|
680 | {"message": "job created", "id": 4},
|
681 | {"message": "job created", "id": 5}
|
682 | ]
|
683 |
|
684 | Note: when inserting multiple jobs in bulk, if one insertion fails Kue will not attempt adding the remaining jobs. The response array will contain the ids of the jobs added successfully, and the last element will be an object describing the error: `{"error": "error reason"}`. It is your responsibility to fix the wrong task and re-submit it and all the subsequent ones.
|
685 |
|
686 |
|
687 | ## Parallel Processing With Cluster
|
688 |
|
689 | The example below shows how you may use [Cluster](http://nodejs.org/api/cluster.html) to spread the job processing load across CPUs. Please see [Cluster module's documentation](http://nodejs.org/api/cluster.html) for more detailed examples on using it.
|
690 |
|
691 | When cluster `.isMaster` the file is being executed in context of the master process, in which case you may perform tasks that you only want once, such as starting the web app bundled with Kue. The logic in the `else` block is executed _per worker_.
|
692 |
|
693 | ```js
|
694 | var kue = require('kue')
|
695 | , cluster = require('cluster')
|
696 | , queue = kue.createQueue();
|
697 |
|
698 | var clusterWorkerSize = require('os').cpus().length;
|
699 |
|
700 | if (cluster.isMaster) {
|
701 | kue.app.listen(3000);
|
702 | for (var i = 0; i < clusterWorkerSize; i++) {
|
703 | cluster.fork();
|
704 | }
|
705 | } else {
|
706 | queue.process('email', 10, function(job, done){
|
707 | var pending = 5
|
708 | , total = pending;
|
709 |
|
710 | var interval = setInterval(function(){
|
711 | job.log('sending!');
|
712 | job.progress(total - pending, total);
|
713 | --pending || done();
|
714 | pending || clearInterval(interval);
|
715 | }, 1000);
|
716 | });
|
717 | }
|
718 | ```
|
719 |
|
720 | This will create an `email` job processor (worker) per each of your machine CPU cores, with each you can handle 10 concurrent email jobs, leading to total `10 * N` concurrent email jobs processed in your `N` core machine.
|
721 |
|
722 | Now when you visit Kue's UI in the browser you'll see that jobs are being processed roughly `N` times faster! (if you have `N` cores).
|
723 |
|
724 | ## Securing Kue
|
725 |
|
726 | Through the use of app mounting you may customize the web application, enabling TLS, or adding additional middleware like Connect's `basicAuth()`.
|
727 |
|
728 | ```js
|
729 | var app = express.createServer({ ... tls options ... });
|
730 | app.use(express.basicAuth('foo', 'bar'));
|
731 | app.use(kue.app);
|
732 | app.listen(3000);
|
733 | ```
|
734 |
|
735 | ## Screencasts
|
736 |
|
737 | - [Introduction](http://www.screenr.com/oyNs) to Kue
|
738 | - API [walkthrough](http://vimeo.com/26963384) to Kue
|
739 |
|
740 | ## License
|
741 |
|
742 | (The MIT License)
|
743 |
|
744 | Copyright (c) 2011 LearnBoost <tj@learnboost.com>
|
745 |
|
746 | Permission is hereby granted, free of charge, to any person obtaining
|
747 | a copy of this software and associated documentation files (the
|
748 | 'Software'), to deal in the Software without restriction, including
|
749 | without limitation the rights to use, copy, modify, merge, publish,
|
750 | distribute, sublicense, and/or sell copies of the Software, and to
|
751 | permit persons to whom the Software is furnished to do so, subject to
|
752 | the following conditions:
|
753 |
|
754 | The above copyright notice and this permission notice shall be
|
755 | included in all copies or substantial portions of the Software.
|
756 |
|
757 | THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
|
758 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
759 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
760 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
761 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
762 | TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
763 | SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|