diff --git a/cmd/p2pool/p2pool.go b/cmd/p2pool/p2pool.go index 23c73ba..e775c44 100644 --- a/cmd/p2pool/p2pool.go +++ b/cmd/p2pool/p2pool.go @@ -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 { diff --git a/p2pool/p2p/server.go b/p2pool/p2p/server.go index 3ea48a6..630fa58 100644 --- a/p2pool/p2p/server.go +++ b/p2pool/p2p/server.go @@ -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() } }() diff --git a/utils/context_ticker.go b/utils/context_ticker.go new file mode 100644 index 0000000..0e64f23 --- /dev/null +++ b/utils/context_ticker.go @@ -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 +}