gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:50:13 25 4
gpt4 key购买 nike

我想在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
# │ │ │ │ │ │
# │ │ │ │ │ │
# * * * * * *

关于javascript - nodejs 应用程序如何在特定时间可靠地执行任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58411126/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com