Skip to content

Instantly share code, notes, and snippets.

@sspencer
Created August 31, 2016 20:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sspencer/275a11e5e560126a0820d8f67c94e968 to your computer and use it in GitHub Desktop.
Save sspencer/275a11e5e560126a0820d8f67c94e968 to your computer and use it in GitHub Desktop.
package command
import (
"fmt"
"net"
"os"
)
const (
message = "This process is already running in SOLO mode."
)
// Solo is used to ensure only 1 instance of the current command runs at the same time.
// This can be used to ensure long cron processes don't start the same application before
// the previous one completes. Make sure to invoke Solo with "go", as it does not
// return. Invoke it like so: "go command.Solo(12345)".
//
// Inspired by : http://timkay.com/solo/solo
func Solo(port int) {
service := fmt.Sprintf(":%d", port)
tcpAddr, err := net.ResolveTCPAddr("tcp4", service)
checkError(err)
// checkError is triggered when second process tries to open this port
listener, err := net.ListenTCP("tcp", tcpAddr)
checkError(err)
for {
conn, err := listener.Accept()
if err != nil {
continue
}
conn.Close()
}
}
func checkError(err error) {
if err != nil {
fmt.Fprintf(os.Stderr, message)
os.Exit(1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment