0

我想使用带有nodejs的议程安排一个简单的任务,但是当它被包装在apiRoutes(快速路由器)中时它没有执行

var apiRoutes = express.Router();
app.use('/api', apiRoutes);

apiRoutes.post('/scheduler/submit', function (req, res) {
    agenda.define('test', function () {
         console.log('Test');
    });

    agenda.on('ready', function () {
         agenda.every('*/1 * * * *', 'test');
         agenda.start();
    });
});

但是,如果我将该代码放在外面,它仍然可以工作。嗯,有什么想法吗?

var apiRoutes = express.Router();
app.use('/api', apiRoutes);

agenda.define('test', function () {
      console.log('Test');
});

agenda.on('ready', function () {
      agenda.every('*/1 * * * *', 'test');
      agenda.start();
});

apiRoutes.post('/scheduler/submit', function (req, res) {
    // Leave blank
});
4

1 回答 1

4

问题是on功能。当您在快速代码中调用时,您正在添加一个对发射器数组agenda.on('ready', ...)的监听,但该信号仅在服务器初始化时连接到您的数据库时才会出现。换句话说,在服务器启动时连接到您的数据库后,它不会再次发出相同的信号,这就是您的 express API 中的代码没有执行的原因。agendareadyagendaagenda

要解决此问题,我建议您确认agenda已成功连接到您的数据库并运行该过程。如果没有,则添加.on('ready', ...)事件侦听器。

样本来源:

var apiRoutes = express.Router();
app.use('/api', apiRoutes);

// Use this to determine if a conneciton has been established between agenda
// and the database
var connectionEstablised = false;

// When the connection is established, set the flag
agenda.on('ready', function() {
    connectionEstablished = true;
});

// It's better practice to have this function defined on your agenda object
// When the server initializes rather than having initializing it only if a POST
// request occurrs.
agenda.define('test', function () {
     console.log('Test');
});



apiRoutes.post('/scheduler/submit', function (req, res) {

    // Only execute this code if you can confirm the connection is established
    if (connectionEstablished) {
        agenda.every('*/1 * * * *', 'test');
        agenda.start();
    }
});
于 2016-12-19T19:19:31.953 回答