master
兔子 1 year ago
parent 0e2d77b297
commit 1218887a1b

@ -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()

@ -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 {

Loading…
Cancel
Save