首页 > 解决方案 > 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() 会被取消。
我怎样才能解决这个问题并可靠地运行任务?

标签: javascriptnode.jsnpm

解决方案


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

您可以使用的 npm 包是node-cron.

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

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

或者

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

用于设置时间的允许字段:

 # ┌────────────── second (optional)
 # │ ┌──────────── minute
 # │ │ ┌────────── hour
 # │ │ │ ┌──────── day of month
 # │ │ │ │ ┌────── month
 # │ │ │ │ │ ┌──── day of week
 # │ │ │ │ │ │
 # │ │ │ │ │ │
 # * * * * * *

推荐阅读