Added utils ContextTicker

This commit is contained in:
DataHoarder 2023-05-23 07:30:25 +02:00
parent 69cfc3f3da
commit 099c393235
Signed by: DataHoarder
SSH key fingerprint: SHA256:OLTRf6Fl87G52SiR7sWLGNzlJt4WOX+tfI2yxo0z7xk
3 changed files with 27 additions and 12 deletions

View file

@ -245,7 +245,7 @@ func main() {
go func() {
contents := make([]byte, 0, 4096)
for range time.Tick(time.Minute * 1) {
for range utils.ContextTick(instance.Context(), time.Minute*1) {
contents = contents[:0]
peerListEntries := instance.Server().PeerList()
slices.SortFunc(peerListEntries, func(a, b *p2p.PeerListEntry) bool {

View file

@ -472,11 +472,7 @@ func (s *Server) Listen() (err error) {
wg.Add(1)
go func() {
defer wg.Done()
for range time.Tick(time.Second * 5) {
if s.close.Load() {
return
}
for range utils.ContextTick(s.ctx, time.Second*5) {
s.UpdatePeerList()
s.UpdateClientConnections()
}
@ -484,11 +480,7 @@ func (s *Server) Listen() (err error) {
wg.Add(1)
go func() {
defer wg.Done()
for range time.Tick(time.Second) {
if s.close.Load() {
return
}
for range utils.ContextTick(s.ctx, time.Second) {
if s.SideChain().PreCalcFinished() {
s.ClearCachedBlocks()
}
@ -499,7 +491,7 @@ func (s *Server) Listen() (err error) {
wg.Add(1)
go func() {
defer wg.Done()
for range time.Tick(time.Hour) {
for range utils.ContextTick(s.ctx, time.Hour) {
s.RefreshOutgoingIPv6()
}
}()

23
utils/context_ticker.go Normal file
View file

@ -0,0 +1,23 @@
package utils
import (
"context"
"time"
)
func ContextTick(ctx context.Context, d time.Duration) <-chan time.Time {
ticker := time.Tick(d)
c := make(chan time.Time, 1)
go func() {
defer close(c)
for {
select {
case <-ctx.Done():
return
case tick := <-ticker:
c <- tick
}
}
}()
return c
}