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

66 lines
1.0 KiB
Go
Raw Normal View History

2018-02-08 14:39:46 +00:00
package signal
import (
"sync"
"time"
)
2018-02-11 22:28:42 +00:00
// PeriodicTask is a task that runs periodically.
2018-02-08 14:39:46 +00:00
type PeriodicTask 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-02-08 14:39:46 +00:00
access sync.Mutex
timer *time.Timer
closed bool
}
func (t *PeriodicTask) checkedExecute() error {
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() {
t.checkedExecute()
})
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-02-08 14:39:46 +00:00
func (t *PeriodicTask) Start() error {
t.access.Lock()
t.closed = false
t.access.Unlock()
if err := t.checkedExecute(); err != nil {
t.closed = true
return err
}
return nil
}
2018-02-11 22:28:42 +00:00
// Close implements common.Runnable.
2018-02-08 14:39:46 +00:00
func (t *PeriodicTask) Close() error {
t.access.Lock()
defer t.access.Unlock()
t.closed = true
if t.timer != nil {
t.timer.Stop()
t.timer = nil
}
return nil
}