@@ -28,27 +28,41 @@ import { WorkflowOrchestratorService } from "@services"
2828import { type CronExpression , parseExpression } from "cron-parser"
2929import { 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+
3145function 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