Minor refactor

This commit is contained in:
Martin Boehm
2022-02-06 21:57:54 +01:00
committed by Martin
parent ec510811cd
commit d5e871818a
7 changed files with 285 additions and 266 deletions

View File

@@ -4,6 +4,7 @@ import (
"encoding/json"
"sort"
"sync"
"sync/atomic"
"time"
)
@@ -16,6 +17,8 @@ const (
DbStateInconsistent
)
var inShutdown int32
// InternalStateColumn contains the data of a db column
type InternalStateColumn struct {
Name string `json:"name"`
@@ -265,3 +268,13 @@ func UnpackInternalState(buf []byte) (*InternalState, error) {
}
return &is, nil
}
// SetInShutdown sets the internal state to in shutdown state
func SetInShutdown() {
atomic.StoreInt32(&inShutdown, 1)
}
// IsInShutdown returns true if in application shutdown state
func IsInShutdown() bool {
return atomic.LoadInt32(&inShutdown) != 0
}

41
common/utils.go Normal file
View File

@@ -0,0 +1,41 @@
package common
import (
"time"
)
// TickAndDebounce calls function f on trigger channel or with tickTime period (whatever is sooner) with debounce
func TickAndDebounce(tickTime time.Duration, debounceTime time.Duration, trigger chan struct{}, f func()) {
timer := time.NewTimer(tickTime)
var firstDebounce time.Time
Loop:
for {
select {
case _, ok := <-trigger:
if !timer.Stop() {
<-timer.C
}
// exit loop on closed input channel
if !ok {
break Loop
}
if firstDebounce.IsZero() {
firstDebounce = time.Now()
}
// debounce for up to debounceTime period
// afterwards execute immediately
if firstDebounce.Add(debounceTime).After(time.Now()) {
timer.Reset(debounceTime)
} else {
timer.Reset(0)
}
case <-timer.C:
// do the action, if not in shutdown, then start the loop again
if !IsInShutdown() {
f()
}
timer.Reset(tickTime)
firstDebounce = time.Time{}
}
}
}