master
兔子 2 years ago
parent 0e2d77b297
commit 1218887a1b

@ -62,6 +62,9 @@ func NewTimer(baseDate time.Time, opts ...TimerOptions) StarTimer {
if op.tasks != nil { if op.tasks != nil {
timer.tasks = append(timer.tasks, op.tasks) timer.tasks = append(timer.tasks, op.tasks)
} }
if op.runLimit > 0 {
timer.runLimit = op.runLimit
}
} }
return timer return timer
} }
@ -71,6 +74,14 @@ func (t *StarTimer) IsRunning() bool {
return t.running 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()) { func (t *StarTimer) AddTask(task func()) {
t.tasks = append(t.tasks, task) t.tasks = append(t.tasks, task)
} }
@ -163,12 +174,16 @@ func (t *StarTimer) Run() error {
t.stopCtx, t.stopFn = context.WithCancel(context.Background()) t.stopCtx, t.stopFn = context.WithCancel(context.Background())
go func() { go func() {
for { for {
if t.runCount+1 >= t.runLimit {
t.Stop()
}
now := time.Now() now := time.Now()
t.mu.Lock() t.mu.Lock()
t.timer = time.NewTimer(t.nextDate.Sub(now)) t.timer = time.NewTimer(t.nextDate.Sub(now))
t.mu.Unlock() t.mu.Unlock()
select { select {
case <-t.timer.C: case <-t.timer.C:
t.runCount++
t.nextDate = t.parseNextDate(t.nextDate, false) t.nextDate = t.parseNextDate(t.nextDate, false)
if t.nextDate.Before(now) { if t.nextDate.Before(now) {
t.Stop() t.Stop()

@ -37,6 +37,8 @@ type StarTimer struct {
stopCtx context.Context stopCtx context.Context
mu *sync.RWMutex mu *sync.RWMutex
running bool running bool
runCount int
runLimit int
repeat []*Repeats repeat []*Repeats
tasks []func() tasks []func()
} }
@ -44,11 +46,18 @@ type StarTimer struct {
type TimerOptions func(option *TimerOption) type TimerOptions func(option *TimerOption)
type TimerOption struct { type TimerOption struct {
idx uint8 idx uint8
repeats *Repeats repeats *Repeats
tasks func() tasks func()
date time.Time date time.Time
repeat Repeat repeat Repeat
runLimit int
}
func WithRunCountLimit(rm int) TimerOptions {
return func(option *TimerOption) {
option.runLimit = rm
}
} }
func WithRepeats(r *Repeats) TimerOptions { func WithRepeats(r *Repeats) TimerOptions {

Loading…
Cancel
Save