gpt4 book ai didi

javascript - 在 Node 中设置日期时间/计时器

转载 作者:行者123 更新时间:2023-11-30 08:26:12 24 4
gpt4 key购买 nike

假设我想设置一个通过 Node.js 运行的定时服务。我真的会使用 setTimeoutsetInterval 大约每分钟运行一次来​​检查时间是否匹配吗?有没有更好的方法来解决这个问题?

更具体地说,我想设置一个给定一天中某个时间的服务,届时它会发送一封电子邮件。

在伪代码中:

setInterval(function(){

// using moment.js for time formatting
var isItTime = new moment().format("HH:mm") === "04:00";

if( isItTime ) {
sendEmail();
}

}, 60 * 1000);

是否有更好或更标准化的方式?

最佳答案

我通常不推荐包,但由于这是一种相对常见的模式,即搜索“node cron job”,我建议利用包来安排重复任务。一个这样的例子是 node-schedule .

关于我推荐它的原因,请参阅文档中的这句话(强调我的):

Node Schedule is for time-based scheduling, not interval-based scheduling. While you can easily bend it to your will, if you only want to do something like "run this function every 5 minutes", you'll find setInterval much easier to use, and far more appropriate. But if you want to, say, "run this function at the :20 and :50 of every hour on the third Tuesday of every month," you'll find that Node Schedule suits your needs better.

关于javascript - 在 Node 中设置日期时间/计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45287638/

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