Compare commits

...
2 Commits
Author SHA1 Message Date
gohumble 0d2814d45c fix typo 2022-03-01 10:24:33 +01:00
gohumble c9b26641ea ⏱ Add Mutex with TTL 2022-03-01 10:19:18 +01:00
2 changed files with 20 additions and 0 deletions
+7
View File
@@ -17,6 +17,7 @@ var defaultTickerCoolDown = time.Second * 10
type ResettableFunctionTicker struct {
Ticker *time.Ticker
ResetChan chan struct{} // channel used to reset the ticker
StopChan chan struct{} // channel used to stop the ticker
duration time.Duration
Started bool
name string
@@ -44,6 +45,7 @@ func GetTicker(name string, option ...ResettableFunctionTickerOption) *Resettabl
func NewResettableFunctionTicker(name string, option ...ResettableFunctionTickerOption) *ResettableFunctionTicker {
t := &ResettableFunctionTicker{
ResetChan: make(chan struct{}, 1),
StopChan: make(chan struct{}, 1),
name: name,
}
@@ -70,6 +72,11 @@ func (t *ResettableFunctionTicker) Do(f func()) {
case <-t.ResetChan:
// reset signal received. creating new ticker.
t.Ticker = time.NewTicker(t.duration)
case <-t.StopChan:
// reset signal received. creating new ticker.
t.Ticker = nil
tickerMap.Remove(t.name)
return
}
}
}()
+13
View File
@@ -3,8 +3,10 @@ package mutex
import (
"context"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
"net/http"
"sync"
"time"
"github.com/gorilla/mux"
@@ -118,8 +120,14 @@ func Lock(s string) {
} else {
m := &sync.Mutex{}
m.Lock()
tick := runtime.NewResettableFunctionTicker(s, runtime.WithDuration(time.Hour))
tick.Do(
func() {
Unlock(s)
})
// write into mutex map
mutexMapSync.Lock()
mutexMap.Set(fmt.Sprintf("ticker_%s", s), tick)
mutexMap.Set(s, m)
mutexMapSync.Unlock()
}
@@ -131,6 +139,11 @@ func Unlock(s string) {
mutexMapSync.Lock()
if m, ok := mutexMap.Get(s); ok {
mutexMap.Remove(s)
tickerKey := fmt.Sprintf("ticker_%s", s)
if tick, ok := mutexMap.Get(tickerKey); ok {
tick.(*runtime.ResettableFunctionTicker).StopChan <- struct{}{}
mutexMap.Remove(tickerKey)
}
m.(*sync.Mutex).Unlock()
log.Tracef("[Mutex] Unlocked %s", s)
} else {