Created
August 2, 2012 01:27
-
-
Save larzconwell/3232287 to your computer and use it in GitHub Desktop.
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 ( | |
"flag" | |
"fmt" | |
"os" | |
"os/exec" | |
"time" | |
) | |
var ( | |
quiet, halt bool | |
interval time.Duration | |
) | |
const defaultInterval = time.Second * 10 | |
const usage = `gwatch 0.1.0 | |
Description: | |
Execute a program periodically | |
Usage: | |
--quiet, -q Only output Stderr messages | |
--halt, -h Halt if a failure occurs | |
--interval, -i <interval> Interval to run command, interval can be in nanoseconds, | |
milliseconds, seconds, minutes and hours (Default 10s) | |
` | |
func init() { | |
flag.BoolVar(&quiet, "quiet", false, "") | |
flag.BoolVar(&quiet, "q", false, "") | |
flag.BoolVar(&halt, "halt", false, "") | |
flag.BoolVar(&halt, "h", false, "") | |
flag.DurationVar(&interval, "interval", defaultInterval, "") | |
flag.DurationVar(&interval, "i", defaultInterval, "") | |
flag.Usage = func() { | |
fmt.Println(usage) | |
} | |
} | |
func main() { | |
flag.Parse() | |
// Show usage if no arguments exist | |
if len(os.Args) <= 1 { | |
fmt.Println(usage) | |
os.Exit(0) | |
} | |
// Slice of arguments | |
commandArgs := flag.Args() | |
// If no command is given error out | |
if len(commandArgs) <= 0 { | |
fmt.Println("gwatch: No command to run") | |
os.Exit(1) | |
} | |
// Look up the command's path | |
commandPath, err := exec.LookPath(commandArgs[0]) | |
if err != nil { | |
fmt.Println(time.Now(), err) | |
os.Exit(1) | |
} | |
// Set commandPath back to the executable | |
commandArgs[0] = commandPath | |
// Call the command when it starts and on ticks | |
runCommand(time.Now(), commandArgs, quiet, halt) | |
// Create interval ticker | |
ticker := time.NewTicker(interval) | |
defer ticker.Stop() | |
// Every time a tick is received from the channel `C` run the command | |
for i := range ticker.C { | |
go runCommand(i, commandArgs, quiet, halt) | |
} | |
} | |
func runCommand(t time.Time, commandArgs []string, quiet, halt bool) { | |
// Set up the command for execution | |
cmd := exec.Command(commandArgs[0], commandArgs[1:]...) | |
// If quiet option isn't used then set Stdout to os.Stdout | |
if !quiet { | |
cmd.Stdout = os.Stdout | |
} | |
if err := cmd.Run(); err != nil && halt { | |
fmt.Println(t, err) | |
os.Exit(1) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment