From b1cba9fdeba901c9d4c7bddd414ed2fd085fa7b0 Mon Sep 17 00:00:00 2001 From: "Carlos R. L. Rodrigues" <37986729+carlos-r-l-rodrigues@users.noreply.github.com> Date: Wed, 6 Aug 2025 11:14:44 -0300 Subject: [PATCH] fix(workflow-engine-inmemory): fix cron job schedule (#13151) --- .changeset/warm-poems-fly.md | 5 +++++ .../utils/workflow-orchestrator-storage.ts | 20 ++++++++++++++++--- 2 files changed, 22 insertions(+), 3 deletions(-) create mode 100644 .changeset/warm-poems-fly.md diff --git a/.changeset/warm-poems-fly.md b/.changeset/warm-poems-fly.md new file mode 100644 index 0000000000..934948df2e --- /dev/null +++ b/.changeset/warm-poems-fly.md @@ -0,0 +1,5 @@ +--- +"@medusajs/workflow-engine-inmemory": patch +--- + +fix(workflow-engine-inmemory): fix cron job schedule diff --git a/packages/modules/workflow-engine-inmemory/src/utils/workflow-orchestrator-storage.ts b/packages/modules/workflow-engine-inmemory/src/utils/workflow-orchestrator-storage.ts index bad9a32d1f..c299e74598 100644 --- a/packages/modules/workflow-engine-inmemory/src/utils/workflow-orchestrator-storage.ts +++ b/packages/modules/workflow-engine-inmemory/src/utils/workflow-orchestrator-storage.ts @@ -28,27 +28,41 @@ import { WorkflowOrchestratorService } from "@services" import { type CronExpression, parseExpression } from "cron-parser" import { WorkflowExecution } from "../models/workflow-execution" +function calculateDelayFromExpression(expression: CronExpression): number { + const nextTime = expression.next().getTime() + const now = Date.now() + const delay = nextTime - now + + // If the calculated delay is negative or zero, get the next occurrence + if (delay <= 0) { + const nextNextTime = expression.next().getTime() + return Math.max(1, nextNextTime - now) + } + + return delay +} + function parseNextExecution( optionsOrExpression: SchedulerOptions | CronExpression | string | number ) { if (typeof optionsOrExpression === "object") { if ("cron" in optionsOrExpression) { const expression = parseExpression(optionsOrExpression.cron) - return expression.next().getTime() - Date.now() + return calculateDelayFromExpression(expression) } if ("interval" in optionsOrExpression) { return optionsOrExpression.interval } - return optionsOrExpression.next().getTime() - Date.now() + return calculateDelayFromExpression(optionsOrExpression) } const result = parseInt(`${optionsOrExpression}`) if (isNaN(result)) { const expression = parseExpression(`${optionsOrExpression}`) - return expression.next().getTime() - Date.now() + return calculateDelayFromExpression(expression) } return result