Skip to content

Commit b1cba9f

Browse files
fix(workflow-engine-inmemory): fix cron job schedule (medusajs#13151)
1 parent b7083b9 commit b1cba9f

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

.changeset/warm-poems-fly.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@medusajs/workflow-engine-inmemory": patch
3+
---
4+
5+
fix(workflow-engine-inmemory): fix cron job schedule

packages/modules/workflow-engine-inmemory/src/utils/workflow-orchestrator-storage.ts

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,27 +28,41 @@ import { WorkflowOrchestratorService } from "@services"
2828
import { type CronExpression, parseExpression } from "cron-parser"
2929
import { WorkflowExecution } from "../models/workflow-execution"
3030

31+
function calculateDelayFromExpression(expression: CronExpression): number {
32+
const nextTime = expression.next().getTime()
33+
const now = Date.now()
34+
const delay = nextTime - now
35+
36+
// If the calculated delay is negative or zero, get the next occurrence
37+
if (delay <= 0) {
38+
const nextNextTime = expression.next().getTime()
39+
return Math.max(1, nextNextTime - now)
40+
}
41+
42+
return delay
43+
}
44+
3145
function parseNextExecution(
3246
optionsOrExpression: SchedulerOptions | CronExpression | string | number
3347
) {
3448
if (typeof optionsOrExpression === "object") {
3549
if ("cron" in optionsOrExpression) {
3650
const expression = parseExpression(optionsOrExpression.cron)
37-
return expression.next().getTime() - Date.now()
51+
return calculateDelayFromExpression(expression)
3852
}
3953

4054
if ("interval" in optionsOrExpression) {
4155
return optionsOrExpression.interval
4256
}
4357

44-
return optionsOrExpression.next().getTime() - Date.now()
58+
return calculateDelayFromExpression(optionsOrExpression)
4559
}
4660

4761
const result = parseInt(`${optionsOrExpression}`)
4862

4963
if (isNaN(result)) {
5064
const expression = parseExpression(`${optionsOrExpression}`)
51-
return expression.next().getTime() - Date.now()
65+
return calculateDelayFromExpression(expression)
5266
}
5367

5468
return result

0 commit comments

Comments
 (0)