← 中文资源

简体中文版本

统计窗口内的 Cron 执行次数

针对简单的 cron 分钟字段,统计时间窗口内的计划执行次数并列出前几次执行,让重叠与负载估算不再是猜测。

阅读英文原文

任务

解析分钟字段(*/N 或固定分钟),在 [from, to) 半开窗口内枚举命中时刻,输出次数与前几次执行时间。

契约

  • 输入:JSON 对象:{ cron: “*/N * * * *” | “M * * * *”, from: ISO 字符串, to: ISO 字符串 },窗口为 [from, to)
  • 输出:JSON 对象:{ count, firstRuns: string[] }

样例

  1. 输入 {"cron":"*/15 * * * *","from":"2026-01-01T00:00:00Z","to":"2026-01-01T01:00:00Z"} -> 期望 {"count":4,"firstRuns":["2026-01-01T00:00:00.000Z","2026-01-01T00:15:00.000Z","2026-01-01T00:30:00.000Z"]}。一小时内命中四次每刻钟执行,且不包含结束边界。
  2. 输入 {"cron":"5 * * * *","from":"2026-01-01T00:00:00Z","to":"2026-01-01T02:00:00Z"} -> 期望 {"count":2,"firstRuns":["2026-01-01T00:05:00.000Z","2026-01-01T01:05:00.000Z"]}。固定分钟的任务每小时只执行一次。

参考实现

function solve({ cron, from, to }) {
      const field = String(cron).split(/\s+/)[0];
      const fromMinute = Math.floor(Date.parse(from) / 60000);
      const toMinute = Math.floor(Date.parse(to) / 60000);
      const isStep = field.startsWith('*/');
      const step = isStep ? Number(field.slice(2)) : 0;
      const runs = [];
      for (let minute = fromMinute; minute < toMinute; minute++) {
        const fires = isStep ? minute % step === 0 : minute % 60 === Number(field);
        if (fires) runs.push(new Date(minute * 60000).toISOString());
      }
      return { count: runs.length, firstRuns: runs.slice(0, 3) };
    }

为什么有效

调度撞车是重复执行工作的常见原因。统计某窗口内的触发次数,能让两个任务争夺同一分钟的情况一目了然。

窗口是半开的;把结束边界算进来会让计数多出一次。