You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-zero/core/executors/delayexecutor.go

48 lines
942 B
Go

4 years ago
package executors
import (
"sync"
"time"
"github.com/zeromicro/go-zero/core/threading"
4 years ago
)
// A DelayExecutor delays a tasks on given delay interval.
4 years ago
type DelayExecutor struct {
fn func()
delay time.Duration
triggered bool
lock sync.Mutex
}
// NewDelayExecutor returns a DelayExecutor with given fn and delay.
4 years ago
func NewDelayExecutor(fn func(), delay time.Duration) *DelayExecutor {
return &DelayExecutor{
fn: fn,
delay: delay,
}
}
// Trigger triggers the task to be executed after given delay, safe to trigger more than once.
4 years ago
func (de *DelayExecutor) Trigger() {
de.lock.Lock()
defer de.lock.Unlock()
if de.triggered {
return
}
de.triggered = true
threading.GoSafe(func() {
timer := time.NewTimer(de.delay)
defer timer.Stop()
<-timer.C
// set triggered to false before calling fn to ensure no triggers are missed.
de.lock.Lock()
de.triggered = false
de.lock.Unlock()
de.fn()
})
}