Skip to content

Commit

Permalink
feat: add MaxIter
Browse files Browse the repository at this point in the history
  • Loading branch information
hum committed Jan 15, 2024
1 parent c1ac4e6 commit cd9242a
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
10 changes: 10 additions & 0 deletions scheduler.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,16 @@ func (s *Scheduler) execTask(task *task, runOnce bool) {
return
}

// Check if the task expired by reaching the maximum
if task.MaxIter > 0 {
if task.MaxIter == task.itercnt {
fmt.Println("task reached max iter")
s.RemoveTask(task.ID)
return
}
task.itercnt++
}

go task.run()
defer func() {
if !runOnce {
Expand Down
13 changes: 13 additions & 0 deletions task.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ type TaskOpts struct {
// Interval for Fn's execution within the scheduler. This is the function's tick.
Interval time.Duration

// Limits the amount of times a single task can be executed in the runtime. After `MaxIter` steps, it will end.
// By default, it is 0 (infinite). Negative values are not allowed.
MaxIter int

// Allows the scheduling based on a CRON string. Overrides `Interval`
Cron string
}
Expand All @@ -51,13 +55,21 @@ type task struct {
// Interval for Fn's execution within the scheduler. This is the function's tick.
Interval time.Duration

// Limits the amount of times a single task can be executed in the runtime. After `MaxIter` steps, it will end.
// By default, it is 0 (infinite). Negative values are not allowed.
MaxIter int

// Allows the scheduling based on a CRON string. Overrides `Interval`
cron *cron.Expr

ctx context.Context
cancel context.CancelFunc

// Internal timer to keep track of ticks
timer *time.Timer

// Counts the current iteration. Only used if `MaxIter` is set. A task will stop once `itercnt == MaxIter`
itercnt int
}

func NewTask(opts TaskOpts) *task {
Expand Down Expand Up @@ -106,6 +118,7 @@ func NewTask(opts TaskOpts) *task {
Fn: opts.Fn,
ErrFn: opts.ErrFn,
Interval: opts.Interval,
MaxIter: opts.MaxIter,
StartTime: opts.StartTime,
EndTime: endTime,
cron: cronExpr,
Expand Down

0 comments on commit cd9242a

Please sign in to comment.