Skip to content

Instantly share code, notes, and snippets.

@Zemnmez
Last active January 2, 2016 00:49
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 Zemnmez/8226068 to your computer and use it in GitHub Desktop.
Save Zemnmez/8226068 to your computer and use it in GitHub Desktop.
package main
import (
"errors"
"flag"
"fmt"
"os"
"os/exec"
"strings"
"time"
)
const format = time.Kitchen
var (
cmd, atTime string
)
type status int
const (
ok status = 0
fail status = 1
)
func main() {
var s status
defer os.Exit(int(s))
flag.StringVar(&cmd, "cmd", "", "Command to run at date.")
flag.StringVar(&atTime, "time", "", "Date or time to run at. Uses time.Parse (http://golang.org/pkg/time/#Parse). Expected format: \""+format+"\".")
flag.Parse()
for inf := range run() {
var err error
switch v := inf.(type) {
case status:
s = v
case error:
_, err = fmt.Fprintf(os.Stderr, "Error: %s\n", v.Error())
case string:
_, err = os.Stdout.Write([]byte(v + "\n"))
}
if err != nil {
panic(fmt.Sprintf("Fatal error: %s\n", err.Error()))
}
}
}
func run() (chn <-chan interface{}) {
c := make(chan interface{})
chn = c
go func() {
defer close(c)
if cmd == "" || atTime == "" {
c <- errors.New("Command or time unspecified")
c <- fail
return
}
t, err := time.Parse(format, atTime)
if err != nil {
c <- err
c <- fail
return
}
n := time.Now()
future := time.Date(n.Year(), n.Month(), n.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), t.Location())
c <- fmt.Sprintf("I'll be back at %+q", future)
time.Sleep(future.Sub(n))
c <- fmt.Sprintf("I'm back, running %+q.", cmd)
spl := strings.Split(cmd, " ")
err = exec.Command(spl[0], spl[1:]...).Start()
if err != nil {
c <- err
c <- fail
return
}
return
}()
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment