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

NodeJS使用node-cron切换滑块对应定时任务时多任务运行如何解决?

问题核心原因
  • 你当前的代码每次触发滑块事件都会创建一个独立的cron任务实例,且旧任务实例被存放在time函数的局部变量task中,函数执行结束后就丢失了旧实例的引用,自然无法通过stop/cancel方法销毁旧任务,最终导致多个任务并行运行
  • node-cron中stop()方法仅暂停任务,任务实例仍然存在,要彻底销毁需要调用destroy()方法
修复方案

将cron任务实例提到全局作用域存储,每次创建新任务前先销毁旧的任务实例即可,修改后的完整代码如下:

const { ipcRenderer } = require("electron");
const cron = require('node-cron');

var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
output.innerHTML = slider.value;
// 全局存储当前运行的cron任务实例
let currentCronTask = null;

slider.oninput = function () {
  output.innerHTML = this.value;
  time();
};

function time() {
  // 先销毁已存在的旧任务
  if (currentCronTask) {
    currentCronTask.destroy();
    currentCronTask = null;
  }

  const slidertime = parseInt(document.getElementById("myRange").value);
  let pattern;

  switch (slidertime) {
    case 15:
      console.log("every 15 min");
      pattern = '0 */15 * * * *' 
      break;
    case 30:
      console.log("every 30 min");
      pattern = '0 */30 * * * *'
      break;
    case 45:
      console.log("every 45 min");
      pattern = '0 */45 * * * *'
      break;
    case 60:
      console.log("every 60 min");
      pattern = '0 */60 * * * *'
      break;
    default:
      // 非法值直接返回,不创建任务
      return;
  }

  // 新任务赋值给全局变量存储
  currentCronTask = cron.schedule(pattern, function () {
    ipcRenderer.send("asynchronous-message", `foo`);
  });
  // 如果需要切换档位后立即执行一次任务,不需要等第一个周期触发,可以改成下面的写法
  // currentCronTask = cron.schedule(pattern, function () {
  //   ipcRenderer.send("asynchronous-message", `foo`);
  // }, { runOnInit: true });
}
time();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 14:57:03