mirror of https://github.com/v2ray/v2ray-core
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
70 lines
1.2 KiB
70 lines
1.2 KiB
7 years ago
|
package task
|
||
7 years ago
|
|
||
|
import (
|
||
|
"sync"
|
||
|
"time"
|
||
|
)
|
||
|
|
||
7 years ago
|
// Periodic is a task that runs periodically.
|
||
|
type Periodic struct {
|
||
7 years ago
|
// Interval of the task being run
|
||
7 years ago
|
Interval time.Duration
|
||
7 years ago
|
// Execute is the task function
|
||
|
Execute func() error
|
||
7 years ago
|
// OnFailure will be called when Execute returns non-nil error
|
||
|
OnError func(error)
|
||
7 years ago
|
|
||
|
access sync.Mutex
|
||
|
timer *time.Timer
|
||
|
closed bool
|
||
|
}
|
||
|
|
||
7 years ago
|
func (t *Periodic) checkedExecute() error {
|
||
7 years ago
|
t.access.Lock()
|
||
|
defer t.access.Unlock()
|
||
|
|
||
|
if t.closed {
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
if err := t.Execute(); err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
t.timer = time.AfterFunc(t.Interval, func() {
|
||
7 years ago
|
if err := t.checkedExecute(); err != nil && t.OnError != nil {
|
||
|
t.OnError(err)
|
||
|
}
|
||
7 years ago
|
})
|
||
|
|
||
|
return nil
|
||
|
}
|
||
|
|
||
7 years ago
|
// Start implements common.Runnable. Start must not be called multiple times without Close being called.
|
||
7 years ago
|
func (t *Periodic) Start() error {
|
||
7 years ago
|
t.access.Lock()
|
||
|
t.closed = false
|
||
|
t.access.Unlock()
|
||
|
|
||
|
if err := t.checkedExecute(); err != nil {
|
||
|
t.closed = true
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
return nil
|
||
|
}
|
||
|
|
||
7 years ago
|
// Close implements common.Closable.
|
||
7 years ago
|
func (t *Periodic) Close() error {
|
||
7 years ago
|
t.access.Lock()
|
||
|
defer t.access.Unlock()
|
||
|
|
||
|
t.closed = true
|
||
|
if t.timer != nil {
|
||
|
t.timer.Stop()
|
||
|
t.timer = nil
|
||
|
}
|
||
|
|
||
|
return nil
|
||
|
}
|