Kue.JS手册

创建作业

第一步使用 kue.createQueue() 创建 作业队列:

var kue = require('kue')
  , jobs = kue.createQueue();

Calling jobs.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.

var job = jobs.create('email', {
    title: 'welcome email for tj'
  , to: '[email protected]'
  , template: 'welcome-email'
}).save( function(err){
   if( !err ) console.log( job.id );
});

作业优先级

To specify the priority of a job, simply invoke the priority() method with a number, or priority name, which is mapped to a number.

jobs.create('email', {
    title: 'welcome email for tj'
  , to: '[email protected]'
  , template: 'welcome-email'
}).priority('high').save();

默认优先级映射如下:

{
    low: 10
  , normal: 0
  , medium: -5
  , high: -10
  , critical: -15
};

失败尝试

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.

 jobs.create('email', {
     title: 'welcome email for tj'
   , to: '[email protected]'
   , template: 'welcome-email'
 }).priority('high').attempts(5).save();

故障延迟

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:

    // Honor job's original delay (if set) at each attempt, defaults to fixed backoff
    job.attempts(3).backoff( true )

    // Override delay value, fixed backoff
    job.attempts(3).backoff( {delay: 60*1000, type:'fixed'} )

    // Enable exponential backoff using original delay (if set)
    job.attempts(3).backoff( {type:'exponential'} )

    // Use a function to get a customized next attempt delay value
    job.attempts(3).backoff( function( attempts, delay ){
      return my_customized_calculated_delay;
    })

In the last scenario, provided function will be called on each re-attempt to get current attempt delay value.

作业日志

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:

job.log('$%d sent to %s', amount, user.name);

作业进度

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):

job.progress(frames, totalFrames);

作业事件

Job-specific events are fired on the Job instances via Redis pubsub. The following events are currently supported:

- `failed` the job has failed and has no remaining attempts
- 'failed attempt' the job has failed, but has remaining attempts yet
- `complete` the job has completed
- `promotion` the job (when delayed) is now queued
- `progress` the job's progress ranging from 0-100

For example this may look something like the following:

var job = jobs.create('video conversion', {
    title: 'converting loki\'s to avi'
  , user: 1
  , frames: 200
});

job.on('complete', function(result){
  console.log("Job completed with data ", result);
}).on('failed', function(){
  console.log("Job failed");
}).on('progress', function(progress){
  process.stdout.write('\r  job #' + job.id + ' ' + progress + '% complete');
});

注意 that Job level events are not guaranteed to be received upon worker process restarts, since the process will lose the reference to the specific Job object. If you want a more reliable event handler look for Queue Events.

队列事件

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:

jobs.on('job complete', function(id,result){
  kue.Job.get(id, function(err, job){
    if (err) return;
    job.remove(function(err){
      if (err) throw err;
      console.log('removed completed job #%d', job.id);
    });
  });
});

The events available are the same as mentioned in "Job Events", however prefixed with "job ".

延迟作业

通过调用 '.delay(ms)' 方法,延迟作业可以预设队列为任意远时间,传递相对于now微秒数字. This automatically flags the Job as "delayed".

var email = jobs.create('email', {
    title: 'Account renewal required'
  , to: '[email protected]'
  , template: 'renewal-email'
}).delay(milliseconds)
  .priority('high')
  .save();

当使用延迟作业时, 我们必须使用计时检测延作业, 如果已经超过预定时间推进他们.Queue#promote(ms,limit)定义了这个 setInterval , 默认每5妙检测前200个作业.

jobs.promote();