1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2025-02-20 23:47:21 -05:00
v2fly/common/signal/timer.go

83 lines
1.3 KiB
Go
Raw Normal View History

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