javascript - 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
. 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
# │ │ │ │ │ │
# │ │ │ │ │ │
# * * * * * *
推荐阅读
- python - 如何自己加入熊猫数据框?
- javascript - 在 ReactJS 中遇到多个活动状态的问题
- powershell - Powershell SQL查询变量
- javascript - 具有意外结果的阵列拼接
- matlab - Matlab在球体上生成热图
- redhawksdr - 使用 RH 2.0.8 运行 USRP_UHD v6.1.0 的问题
- json - Dart:具有 .fromJson 构造函数的泛型
- java - 正则表达式从字符串中获取第三个元素
- jenkins - 用于微服务系统的 Jenkins CI/CD 设置
- sql - 仅在案例语句中添加年份得到无效数字错误 - ORA-01722