| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 | 
							- package signal
 
- import (
 
- 	"context"
 
- 	"sync"
 
- 	"time"
 
- 	"v2ray.com/core/common"
 
- 	"v2ray.com/core/common/task"
 
- )
 
- type ActivityUpdater interface {
 
- 	Update()
 
- }
 
- type ActivityTimer struct {
 
- 	sync.RWMutex
 
- 	updated   chan struct{}
 
- 	checkTask *task.Periodic
 
- 	onTimeout func()
 
- }
 
- 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.Lock()
 
- 	defer t.Unlock()
 
- 	if t.onTimeout != nil {
 
- 		t.onTimeout()
 
- 	}
 
- 	if t.checkTask != nil {
 
- 		t.checkTask.Close()
 
- 		t.checkTask = nil
 
- 	}
 
- }
 
- func (t *ActivityTimer) SetTimeout(timeout time.Duration) {
 
- 	if timeout == 0 {
 
- 		t.finish()
 
- 	}
 
- 	t.Lock()
 
- 	if t.checkTask != nil {
 
- 		t.checkTask.Close() // nolint: errcheck
 
- 	}
 
- 	t.checkTask = &task.Periodic{
 
- 		Interval: timeout,
 
- 		Execute:  t.check,
 
- 	}
 
- 	t.Unlock()
 
- 	t.Update()
 
- 	common.Must(t.checkTask.Start())
 
- }
 
- 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
 
- }
 
 
  |