Created
September 26, 2024 17:14
-
-
Save ErikKalkoken/b776dac83222248b0e644961911cb4b5 to your computer and use it in GitHub Desktop.
Example for using a named mutex with github.com/juju/mutex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"errors" | |
"log" | |
"os" | |
"os/signal" | |
"syscall" | |
"time" | |
"github.com/juju/mutex/v2" | |
) | |
type realtime struct{} | |
func (r realtime) After(d time.Duration) <-chan time.Time { | |
c := make(chan time.Time) | |
go func() { | |
time.Sleep(d) | |
c <- time.Now() | |
}() | |
return c | |
} | |
func (r realtime) Now() time.Time { | |
return time.Now() | |
} | |
func main() { | |
log.Println("Trying to acquire mutex...") | |
r, err := mutex.Acquire(mutex.Spec{Name: "dummy123", Clock: realtime{}, Delay: 100 * time.Millisecond, Timeout: 250 * time.Millisecond}) | |
if errors.Is(err, mutex.ErrTimeout) { | |
log.Println("There is already an instance running") | |
os.Exit(1) | |
} else if err != nil { | |
log.Fatal(err) | |
} | |
defer r.Release() | |
log.Println("Mutex acquired. Running...") | |
sc := make(chan os.Signal, 1) | |
signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt) | |
<-sc | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment