1
mirror of https://github.com/XTLS/Xray-core.git synced 2025-12-12 12:42:26 +04:00
Files
xray-core/common/signal/timer.go

86 lines
1.4 KiB
Go
Raw Normal View History

2020-11-25 19:01:53 +08:00
package signal
import (
"context"
"sync"
"sync/atomic"
2020-11-25 19:01:53 +08:00
"time"
2020-12-04 09:36:16 +08:00
"github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/task"
2020-11-25 19:01:53 +08:00
)
type ActivityUpdater interface {
Update()
}
type ActivityTimer struct {
mu sync.RWMutex
2020-11-25 19:01:53 +08:00
updated chan struct{}
checkTask *task.Periodic
onTimeout func()
consumed atomic.Bool
once sync.Once
2020-11-25 19:01:53 +08:00
}
func (t *ActivityTimer) Update() {
select {
case t.updated <- struct{}{}:
default:
}
}
func (t *ActivityTimer) check() error {
select {
case <-t.updated:
default:
t.finish()
}
return nil
}
func (t *ActivityTimer) finish() {
t.once.Do(func() {
t.consumed.Store(true)
t.mu.Lock()
defer t.mu.Unlock()
2020-11-25 19:01:53 +08:00
common.CloseIfExists(t.checkTask)
2020-11-25 19:01:53 +08:00
t.onTimeout()
})
2020-11-25 19:01:53 +08:00
}
func (t *ActivityTimer) SetTimeout(timeout time.Duration) {
if t.consumed.Load() {
return
}
2020-11-25 19:01:53 +08:00
if timeout == 0 {
t.finish()
return
}
t.mu.Lock()
defer t.mu.Unlock()
// double check, just in case
if t.consumed.Load() {
return
}
newCheckTask := &task.Periodic{
2020-11-25 19:01:53 +08:00
Interval: timeout,
Execute: t.check,
}
common.CloseIfExists(t.checkTask)
t.checkTask = newCheckTask
2020-11-25 19:01:53 +08:00
t.Update()
common.Must(newCheckTask.Start())
2020-11-25 19:01:53 +08:00
}
func CancelAfterInactivity(ctx context.Context, cancel context.CancelFunc, timeout time.Duration) *ActivityTimer {
timer := &ActivityTimer{
updated: make(chan struct{}, 1),
onTimeout: cancel,
}
timer.SetTimeout(timeout)
return timer
}