v2ray-core/common/signal/timer.go

83 lines
1.3 KiB
Go
Raw Normal View History

2017-01-31 11:42:05 +00:00
package signal
import (
"context"
2018-05-27 12:42:53 +00:00
"sync"
2017-01-31 11:42:05 +00:00
"time"
2018-05-27 12:42:53 +00:00
"v2ray.com/core/common"
"v2ray.com/core/common/task"
2017-01-31 11:42:05 +00:00
)
type ActivityUpdater interface {
2017-04-04 08:24:38 +00:00
Update()
}
type ActivityTimer struct {
2018-05-27 12:42:53 +00:00
sync.RWMutex
updated chan struct{}
checkTask *task.Periodic
onTimeout func()
2017-01-31 11:42:05 +00:00
}
func (t *ActivityTimer) Update() {
2017-01-31 11:42:05 +00:00
select {
2018-02-08 14:39:46 +00:00
case t.updated <- struct{}{}:
2017-01-31 11:42:05 +00:00
default:
}
}
2018-05-27 12:42:53 +00:00
func (t *ActivityTimer) check() error {
2018-02-06 10:16:49 +00:00
select {
2018-05-27 12:42:53 +00:00
case <-t.updated:
default:
t.finish()
2018-02-06 10:16:49 +00:00
}
2018-05-27 12:42:53 +00:00
return nil
}
2018-05-27 12:42:53 +00:00
func (t *ActivityTimer) finish() {
t.Lock()
defer t.Unlock()
2017-12-14 16:39:58 +00:00
2018-05-27 12:42:53 +00:00
if t.onTimeout != nil {
t.onTimeout()
2018-05-28 12:02:09 +00:00
t.onTimeout = nil
2017-12-14 16:39:58 +00:00
}
2018-05-27 12:42:53 +00:00
if t.checkTask != nil {
2018-05-28 11:55:20 +00:00
t.checkTask.Close() // nolint: errcheck
2018-05-27 12:42:53 +00:00
t.checkTask = nil
}
}
2017-12-14 16:39:58 +00:00
2018-05-27 12:42:53 +00:00
func (t *ActivityTimer) SetTimeout(timeout time.Duration) {
if timeout == 0 {
t.finish()
2018-05-28 11:55:20 +00:00
return
2018-05-27 12:42:53 +00:00
}
2017-11-23 13:58:35 +00:00
2018-06-22 09:19:33 +00:00
checkTask := &task.Periodic{
Interval: timeout,
Execute: t.check,
}
2018-05-27 12:42:53 +00:00
t.Lock()
2017-05-08 15:09:21 +00:00
2018-05-27 12:42:53 +00:00
if t.checkTask != nil {
t.checkTask.Close() // nolint: errcheck
}
2018-06-22 09:19:33 +00:00
t.checkTask = checkTask
2018-05-27 12:42:53 +00:00
t.Unlock()
t.Update()
2018-06-22 09:19:33 +00:00
common.Must(checkTask.Start())
2017-01-31 11:42:05 +00:00
}
2017-11-14 23:36:14 +00:00
func CancelAfterInactivity(ctx context.Context, cancel context.CancelFunc, timeout time.Duration) *ActivityTimer {
timer := &ActivityTimer{
2018-05-27 12:42:53 +00:00
updated: make(chan struct{}, 1),
onTimeout: cancel,
2017-01-31 11:42:05 +00:00
}
2018-05-27 12:42:53 +00:00
timer.SetTimeout(timeout)
2017-11-14 23:36:14 +00:00
return timer
2017-01-31 11:42:05 +00:00
}