最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

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

IT培训 admin 4浏览 0评论

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
 # │ │ │ │ │ │
 # │ │ │ │ │ │
 # * * * * * *

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. 暂无评论