summaryrefslogtreecommitdiff
path: root/vendor/github.com/pion/turn/v2/internal/client/periodic_timer.go
blob: fcd56787077d5d4b28a859901d59151afd72a806 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package client

import (
	"sync"
	"time"
)

// PeriodicTimerTimeoutHandler is a handler called on timeout
type PeriodicTimerTimeoutHandler func(timerID int)

// PeriodicTimer is a periodic timer
type PeriodicTimer struct {
	id             int
	interval       time.Duration
	timeoutHandler PeriodicTimerTimeoutHandler
	stopFunc       func()
	mutex          sync.RWMutex
}

// NewPeriodicTimer create a new timer
func NewPeriodicTimer(id int, timeoutHandler PeriodicTimerTimeoutHandler, interval time.Duration) *PeriodicTimer {
	return &PeriodicTimer{
		id:             id,
		interval:       interval,
		timeoutHandler: timeoutHandler,
	}
}

// Start starts the timer.
func (t *PeriodicTimer) Start() bool {
	t.mutex.Lock()
	defer t.mutex.Unlock()

	// this is a noop if the timer is always running
	if t.stopFunc != nil {
		return false
	}

	cancelCh := make(chan struct{})

	go func() {
		canceling := false

		for !canceling {
			timer := time.NewTimer(t.interval)

			select {
			case <-timer.C:
				t.timeoutHandler(t.id)
			case <-cancelCh:
				canceling = true
				timer.Stop()
			}
		}
	}()

	t.stopFunc = func() {
		close(cancelCh)
	}

	return true
}

// Stop stops the timer.
func (t *PeriodicTimer) Stop() {
	t.mutex.Lock()
	defer t.mutex.Unlock()

	if t.stopFunc != nil {
		t.stopFunc()
		t.stopFunc = nil
	}
}

// IsRunning tests if the timer is running.
// Debug purpose only
func (t *PeriodicTimer) IsRunning() bool {
	t.mutex.RLock()
	defer t.mutex.RUnlock()

	return (t.stopFunc != nil)
}