1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-07-01 11:35:23 +00:00
v2fly/common/task/periodic.go

80 lines
1.3 KiB
Go
Raw Normal View History

2018-05-27 11:02:29 +00:00
package task
2018-02-08 14:39:46 +00:00
import (
"sync"
"time"
)
2018-05-27 11:02:29 +00:00
// Periodic is a task that runs periodically.
type Periodic struct {
2018-02-11 22:28:42 +00:00
// Interval of the task being run
2018-02-08 14:39:46 +00:00
Interval time.Duration
2018-02-11 22:28:42 +00:00
// Execute is the task function
Execute func() error
2018-04-11 14:15:29 +00:00
// OnFailure will be called when Execute returns non-nil error
OnError func(error)
2018-02-08 14:39:46 +00:00
2018-05-27 12:42:53 +00:00
access sync.RWMutex
2018-02-08 14:39:46 +00:00
timer *time.Timer
closed bool
}
2018-05-27 12:42:53 +00:00
func (t *Periodic) setClosed(f bool) {
2018-02-08 14:39:46 +00:00
t.access.Lock()
2018-05-27 12:42:53 +00:00
t.closed = f
t.access.Unlock()
}
func (t *Periodic) hasClosed() bool {
t.access.RLock()
defer t.access.RUnlock()
return t.closed
}
2018-02-08 14:39:46 +00:00
2018-05-27 12:42:53 +00:00
func (t *Periodic) checkedExecute() error {
if t.hasClosed() {
2018-02-08 14:39:46 +00:00
return nil
}
if err := t.Execute(); err != nil {
return err
}
2018-05-27 12:42:53 +00:00
t.access.Lock()
2018-02-08 14:39:46 +00:00
t.timer = time.AfterFunc(t.Interval, func() {
2018-04-11 14:15:29 +00:00
if err := t.checkedExecute(); err != nil && t.OnError != nil {
t.OnError(err)
}
2018-02-08 14:39:46 +00:00
})
2018-05-27 12:42:53 +00:00
t.access.Unlock()
2018-02-08 14:39:46 +00:00
return nil
}
2018-02-11 22:28:42 +00:00
// Start implements common.Runnable. Start must not be called multiple times without Close being called.
2018-05-27 11:02:29 +00:00
func (t *Periodic) Start() error {
2018-05-27 12:42:53 +00:00
t.setClosed(false)
2018-02-08 14:39:46 +00:00
if err := t.checkedExecute(); err != nil {
2018-05-27 12:42:53 +00:00
t.setClosed(true)
2018-02-08 14:39:46 +00:00
return err
}
return nil
}
2018-04-03 09:11:54 +00:00
// Close implements common.Closable.
2018-05-27 11:02:29 +00:00
func (t *Periodic) Close() error {
2018-02-08 14:39:46 +00:00
t.access.Lock()
defer t.access.Unlock()
t.closed = true
if t.timer != nil {
t.timer.Stop()
t.timer = nil
}
return nil
}