【问题标题】:How to schedule process in the way that it should run immediately for the first time and run with scheduled time from second time in node js如何以第一次应立即运行并在节点 js 中从第二次开始按预定时间运行的方式调度进程
【发布时间】:2018-03-02 06:45:34
【问题描述】:

我尝试使用 node-schedule 包 [https://www.npmjs.com/package/node-schedule][1]

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

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

但是,如果我安排 10 分钟并在 10 分钟后启动它正在处理的进程。 就我而言,我需要第一次运行该进程,然后它应该按照预定时间运行。

这类问题有解决办法吗?

提前致谢..

【问题讨论】:

  • 到目前为止你做了什么?显示您的代码。
  • 您是否尝试过在调度之前先运行“进程”?
  • 我已经更新了代码请查看@timiTao
  • 是的,我试过了,但我需要的问题是@KhauriMcClain 问题中的解释
  • 我是 nodejs 新手,不确定是否可以完成,我很想知道是否有可能。我通常会在安排之前对其进行测试。

标签: node.js


【解决方案1】:

有办法的,刚刚找到了

 let startTime = new Date(Date.now()) ;
 var j = schedule.scheduleJob({ start: startTime, rule:'42 * * * *'}, 
         function(){
         console.log('The answer to life, the universe, and everything!');
       });

希望这会有所帮助 请参阅node-schedule的此文档

【讨论】:

  • 首先,很抱歉延迟回复。我试过了,但没有用:|它是按照上面提到的规则开始的。
【解决方案2】:

您可以使用来自https://github.com/kelektiv/node-cron 的代码。

然后您可以在启动 nodejs 程序的第二次触发 crontab 作业。 crontab 作业之后会以一定的间隔运行。

这是在创建 crontab 工作时立即运行作业的示例。

const CronJob = require('cron').CronJob;
const job = new CronJob({
  cronTime: '0 */5 * * * *',
  onTick: () => console.log(`Round at ${new Date()}`);
  runOnInit: true
});

job.start();

在上面的代码中,“console.log”将在我启动程序时运行。然后它将每 5 分钟运行一次。更多用法可以参考提供的lib。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-26
    • 1970-01-01
    相关资源
    最近更新 更多