You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Node.js中设置每日凌晨3点执行定时任务?

实现每天凌晨3点执行函数的几种方案

纯JavaScript实现(无额外依赖)

不需要引入任何库,通过计算时间差结合setTimeout实现,避免setInterval的累积误差问题:

// 计算距离下一次凌晨3点的毫秒数
function getNextDelay() {
  const now = new Date();
  const target = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 3, 0, 0);
  // 如果当前时间已经过了今天3点,就设置为明天的3点
  if (now > target) {
    target.setDate(target.getDate() + 1);
  }
  return target.getTime() - now.getTime();
}

// 执行任务并循环调度
async function scheduleUpdate() {
  await updateData();
  // 完成本次任务后,调度下一次
  setTimeout(scheduleUpdate, getNextDelay());
}

// 启动第一次调度
setTimeout(scheduleUpdate, getNextDelay());

Node.js环境下使用node-schedule库(更简洁可靠)

如果是在Node.js项目中,使用专门的定时任务库会更直观,也能处理更多复杂的时间规则:

  1. 先安装依赖:
npm install node-schedule
  1. 编写调度代码:
const schedule = require('node-schedule');

// 每天凌晨3点执行
schedule.scheduleJob('0 0 3 * * *', async () => {
  await updateData();
});

时间规则说明:0 0 3 * * * 分别对应 秒 分 时 日 月 周,这里指定的是每天3点0分0秒执行。

内容的提问来源于stack exchange,提问作者admin admin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 09:23:07