Skip to content

Commit

Permalink
Implement a timer reset for channel cleanup & also use just one gorou…
Browse files Browse the repository at this point in the history
…tine
  • Loading branch information
quackduck committed May 3, 2022
1 parent 4f9eb72 commit dcb9a6b
Showing 1 changed file with 24 additions and 2 deletions.
26 changes: 24 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -392,10 +392,32 @@ func cleanupRoomInstant(r *Room) {
}
}

var cleanupMap = make(map[*Room]chan bool, 5)

func cleanupRoom(r *Room) {
if ch, ok := cleanupMap[r]; ok {
ch <- true // reset timer
return
}
go func() {
time.Sleep(time.Hour * 24)
cleanupRoomInstant(r)
ch := make(chan bool) // no buffer needed
cleanupMap[r] = ch
timer := time.NewTimer(time.Hour * 24)
for {
select {
case <-ch: // need a reset?
if !timer.Stop() {
<-timer.C
}
timer.Reset(time.Hour * 24)
// no return, carry on to the next select
case <-timer.C:
delete(cleanupMap, r)
timer.Stop()
cleanupRoomInstant(r)
return // done!
}
}
}()
}

Expand Down

0 comments on commit dcb9a6b

Please sign in to comment.