mirror of
https://github.com/v2fly/v2ray-core.git
synced 2025-01-17 23:06:30 -05:00
non-blocking timer. Fixes #848
This commit is contained in:
parent
3a0f211c22
commit
ede2c39967
@ -12,6 +12,7 @@ type ActivityUpdater interface {
|
|||||||
type ActivityTimer struct {
|
type ActivityTimer struct {
|
||||||
updated chan bool
|
updated chan bool
|
||||||
timeout chan time.Duration
|
timeout chan time.Duration
|
||||||
|
closing chan bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *ActivityTimer) Update() {
|
func (t *ActivityTimer) Update() {
|
||||||
@ -22,11 +23,17 @@ func (t *ActivityTimer) Update() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (t *ActivityTimer) SetTimeout(timeout time.Duration) {
|
func (t *ActivityTimer) SetTimeout(timeout time.Duration) {
|
||||||
t.timeout <- timeout
|
select {
|
||||||
|
case <-t.closing:
|
||||||
|
case t.timeout <- timeout:
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *ActivityTimer) run(ctx context.Context, cancel context.CancelFunc) {
|
func (t *ActivityTimer) run(ctx context.Context, cancel context.CancelFunc) {
|
||||||
defer cancel()
|
defer func() {
|
||||||
|
cancel()
|
||||||
|
close(t.closing)
|
||||||
|
}()
|
||||||
|
|
||||||
timeout := <-t.timeout
|
timeout := <-t.timeout
|
||||||
if timeout == 0 {
|
if timeout == 0 {
|
||||||
@ -66,6 +73,7 @@ func CancelAfterInactivity(ctx context.Context, cancel context.CancelFunc, timeo
|
|||||||
timer := &ActivityTimer{
|
timer := &ActivityTimer{
|
||||||
timeout: make(chan time.Duration, 1),
|
timeout: make(chan time.Duration, 1),
|
||||||
updated: make(chan bool, 1),
|
updated: make(chan bool, 1),
|
||||||
|
closing: make(chan bool),
|
||||||
}
|
}
|
||||||
timer.timeout <- timeout
|
timer.timeout <- timeout
|
||||||
go timer.run(ctx, cancel)
|
go timer.run(ctx, cancel)
|
||||||
|
@ -32,3 +32,15 @@ func TestActivityTimerUpdate(t *testing.T) {
|
|||||||
assert(ctx.Err(), IsNotNil)
|
assert(ctx.Err(), IsNotNil)
|
||||||
runtime.KeepAlive(timer)
|
runtime.KeepAlive(timer)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestActivityTimerNonBlocking(t *testing.T) {
|
||||||
|
assert := With(t)
|
||||||
|
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
timer := CancelAfterInactivity(ctx, cancel, 0)
|
||||||
|
time.Sleep(time.Second * 1)
|
||||||
|
assert(ctx, HasDone)
|
||||||
|
timer.SetTimeout(0)
|
||||||
|
timer.SetTimeout(1)
|
||||||
|
timer.SetTimeout(2)
|
||||||
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user