mirror of
https://github.com/v2fly/v2ray-core.git
synced 2025-12-28 13:05:28 -05:00
unified task package
This commit is contained in:
@@ -1,69 +0,0 @@
|
||||
package signal
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// PeriodicTask is a task that runs periodically.
|
||||
type PeriodicTask struct {
|
||||
// Interval of the task being run
|
||||
Interval time.Duration
|
||||
// Execute is the task function
|
||||
Execute func() error
|
||||
// OnFailure will be called when Execute returns non-nil error
|
||||
OnError func(error)
|
||||
|
||||
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() {
|
||||
if err := t.checkedExecute(); err != nil && t.OnError != nil {
|
||||
t.OnError(err)
|
||||
}
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Start implements common.Runnable. Start must not be called multiple times without Close being called.
|
||||
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
|
||||
}
|
||||
|
||||
// Close implements common.Closable.
|
||||
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
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
package signal_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"v2ray.com/core/common"
|
||||
. "v2ray.com/core/common/signal"
|
||||
. "v2ray.com/ext/assert"
|
||||
)
|
||||
|
||||
func TestPeriodicTaskStop(t *testing.T) {
|
||||
assert := With(t)
|
||||
|
||||
value := 0
|
||||
task := &PeriodicTask{
|
||||
Interval: time.Second * 2,
|
||||
Execute: func() error {
|
||||
value++
|
||||
return nil
|
||||
},
|
||||
}
|
||||
common.Must(task.Start())
|
||||
time.Sleep(time.Second * 5)
|
||||
common.Must(task.Close())
|
||||
assert(value, Equals, 3)
|
||||
time.Sleep(time.Second * 4)
|
||||
assert(value, Equals, 3)
|
||||
}
|
||||
Reference in New Issue
Block a user