最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

nodejs应用程序如何在特定时间可靠地执行任务?

运维笔记admin9浏览0评论

nodejs应用程序如何在特定时间可靠地执行任务?

nodejs应用程序如何在特定时间可靠地执行任务?

我想在特定时间在nodejs应用中执行任务。因此,我使用Timer编写了如下所示的源代码。

 var _to_execute_time = 1571221163000;   //The timestamp to execute the task.  
 var _current_timestamp = Date.now();   //The current timestamp.  
//Scheduling the task using setTimeout();

 setTimeout(task_function,  _to_execute_time - _current_timestamp);  

问题是,如果系统在执行任务之前重新启动,则setTimeout()将被取消。如何解决此问题并可靠地运行任务?

回答如下:

您可以使用node-cron。烤架将在指定的时间运行。

您可以使用的包是node-cron

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

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

OR

cron.schedule('0 11 * * *', () => {
  console.log('running a task at 11:00 AM');
});

允许设置时间的字段:

 # ┌────────────── second (optional)
 # │ ┌──────────── minute
 # │ │ ┌────────── hour
 # │ │ │ ┌──────── day of month
 # │ │ │ │ ┌────── month
 # │ │ │ │ │ ┌──── day of week
 # │ │ │ │ │ │
 # │ │ │ │ │ │
 # * * * * * *
发布评论

评论列表(0)

  1. 暂无评论