在nodejs环回中安排cron作业

时间:2016-05-19 13:21:07

标签: angularjs node.js loopbackjs

如何使用loopback框架在nodejs中安排cron作业。

在服务中,我从API中定义API,然后进入模块并执行操作。但我不知道如何在app.js文件中安排它。

var http = require('http');
var schedule = require('node-schedule');

var j = schedule.scheduleJob('* * * * *', function(){
  console.log('The answer to life, the universe, and everything!');
});

我试过这个,但它没有运行。

4 个答案:

答案 0 :(得分:3)

只需在server / boot中添加一个不在app.js中的新文件。

module.exports = function(app) {
 var http = require('http');
var schedule = require('node-schedule');

var j = schedule.scheduleJob('* * * * *', function(){
  console.log('The answer to life, the universe, and everything!');
});
};

答案 1 :(得分:0)

节点计划,它是节点的类Cron计划,还提供了可以使用的对象文字语法。

在你的问题中,你注意到你正在使用它:

var j = schedule.scheduleJob('* * * * *', function(){
  console.log('The answer to life, the universe, and everything!');
});

但是,你可以使用更像这样的东西:

var j = schedule.scheduleJob({hour: 14, minute: 30, dayOfWeek: 0}, function(){
    console.log('Time for tea!');
});

这只是一个简短的例子,因为我不知道你要做什么的细节,但你需要在Loopback服务器上创建一个API /远程方法,你可以将输入作为JSON传递,如:

{
    hour: 1,
    minute: 30,
    second: 0
}

然后,您的应用会调用您刚刚创建的公开API。希望这有帮助,如果您有任何其他问题,请告诉我。

答案 2 :(得分:0)

我认为你应该把你的代码放在服务器/启动或客户端/启动上,即 crons.js

const schedule = require('node-schedule');

module.exports = (app) => {
     console.log("running job scheduler.."); 
     var job = schedule.scheduleJob('*/1 * * * *', function(){
         console.log('The answer to life, the universe, and everything!');
     });
}

上面的示例代码将每隔一分钟运行一次调度程序。您可能需要查看node-schedule here

的文档

答案 3 :(得分:0)

Loopback(服务器)应用程序不适合这个。您可以在服务器的上下文之外使用模型(例如,简单的节点脚本),如下所示:

var cron = require('node-cron');

cron.schedule('* * * * *', function(){
  console.log('running a task every minute');
});

更多信息:https://hackernoon.com/nodejs-javascript-cron-cron-jobs-cronjob-reactjs-scheduler-schedule-example-tutorial-25bcbe23bc6b