From 1218887a1be0d41d6b2251f17be42cd0cc0a29aa Mon Sep 17 00:00:00 2001 From: ren yuze Date: Wed, 19 Apr 2023 10:44:42 +0800 Subject: [PATCH] update --- timer.go | 15 +++++++++++++++ typed.go | 19 ++++++++++++++----- 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/timer.go b/timer.go index efa1884..2a52729 100644 --- a/timer.go +++ b/timer.go @@ -62,6 +62,9 @@ func NewTimer(baseDate time.Time, opts ...TimerOptions) StarTimer { if op.tasks != nil { timer.tasks = append(timer.tasks, op.tasks) } + if op.runLimit > 0 { + timer.runLimit = op.runLimit + } } return timer } @@ -71,6 +74,14 @@ func (t *StarTimer) IsRunning() bool { return t.running } +func (t *StarTimer) SetRunCountLimit(c int) { + t.runLimit = c +} + +func (t *StarTimer) RunCountLimit() int { + return t.runLimit +} + func (t *StarTimer) AddTask(task func()) { t.tasks = append(t.tasks, task) } @@ -163,12 +174,16 @@ func (t *StarTimer) Run() error { t.stopCtx, t.stopFn = context.WithCancel(context.Background()) go func() { for { + if t.runCount+1 >= t.runLimit { + t.Stop() + } now := time.Now() t.mu.Lock() t.timer = time.NewTimer(t.nextDate.Sub(now)) t.mu.Unlock() select { case <-t.timer.C: + t.runCount++ t.nextDate = t.parseNextDate(t.nextDate, false) if t.nextDate.Before(now) { t.Stop() diff --git a/typed.go b/typed.go index ac605dc..bfc2544 100644 --- a/typed.go +++ b/typed.go @@ -37,6 +37,8 @@ type StarTimer struct { stopCtx context.Context mu *sync.RWMutex running bool + runCount int + runLimit int repeat []*Repeats tasks []func() } @@ -44,11 +46,18 @@ type StarTimer struct { type TimerOptions func(option *TimerOption) type TimerOption struct { - idx uint8 - repeats *Repeats - tasks func() - date time.Time - repeat Repeat + idx uint8 + repeats *Repeats + tasks func() + date time.Time + repeat Repeat + runLimit int +} + +func WithRunCountLimit(rm int) TimerOptions { + return func(option *TimerOption) { + option.runLimit = rm + } } func WithRepeats(r *Repeats) TimerOptions {