nodejs议程重复同样的工作

时间:2015-07-09 17:38:30

标签: javascript node.js

在我的代码agendasetup.js中我有下面的输出。所以command-0,target-0等而不是command-1,target-1等等如何告诉议程运行不同的工作?

  

$ node agendasetup.js

命令-1 目标-1 时间1 宿主

命令-1 目标-1 时间1 宿主

agendasetup.js:

var config = require('./../config/config');
var devagenda = require('./../modules/agendajob');
var Agenda = require('agenda');
var agenda = new Agenda({db: { address: config.agenda_uri}});

for (i=0; i<2; i++) {
    command = 'command-'+i;target = 'target-'+i;
    time = 'time-'+i; host='Host';
    agenda.define('renew cert', function(job, done) {
        devagenda(command, target, time, host);
        done();
    });
    agenda.schedule('in 5 seconds', 'renew cert');
    agenda.start();
}

./../模块/ agendajob

module.exports = function devagenda(command,target, time, host) {
    console.log(command+'\n'+target+'\n'+ time+'\n'+host+'\n');
};

1 个答案:

答案 0 :(得分:1)

由于您正在使用节点,并假设它是更新版本的节点,您可以通过在启动命令中添加--harmony来启用和声标志,然后对脚本进行一些修改使用新的es6 let语法来修复for循环范围问题。

'use strict';
var config = require('./../config/config');
var devagenda = require('./../modules/agendajob');
var Agenda = require('agenda');
var agenda = new Agenda({db: { address: config.agenda_uri}});

for (let i=0; i<2; i++) {
    let command = 'command-'+i;
    let target = 'target-'+i;
    let time = 'time-'+i; 
    let host='Host';
    let jobname = command+target+time
    agenda.define(jobname, function(job, done) {
        devagenda(command, target, time, host);
        done();
    });
    agenda.schedule('in 5 seconds', 'renew cert');
    agenda.start();
}

对于较旧版本的节点(或没有和声标志的用法),您可以在for循环中使用iife。

var config = require('./../config/config');
var devagenda = require('./../modules/agendajob');
var Agenda = require('agenda');
var agenda = new Agenda({db: { address: config.agenda_uri}});

for (i=0; i<2; i++) {
    (function (i) {
        var command = 'command-'+i;
        var target = 'target-'+i;
        var time = 'time-'+i;
        var host='Host';
        agenda.define('renew cert', function(job, done) {
            devagenda(command, target, time, host);
            done();
        });
        agenda.schedule('in 5 seconds', 'renew cert');
        agenda.start();
    }(i));
}