如何在 nodejs 的 express apiRoutes 中包装 Agenda

How to wrap Agenda in express apiRoutes in nodejs

我想使用 Agenda 和 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
});

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

要解决此问题,我建议您确认 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();
    }
});