mirror of
https://github.com/trezor/blockbook.git
synced 2026-02-20 00:51:39 +01:00
Minor refactor
This commit is contained in:
@@ -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
41
common/utils.go
Normal 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{}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user