Created
August 31, 2016 20:17
-
-
Save sspencer/275a11e5e560126a0820d8f67c94e968 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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