Skip to content

Instantly share code, notes, and snippets.

@syfun
Last active January 19, 2017 06:47
Show Gist options
  • Save syfun/e443157eebb707ccc8506ba3fa861ddc to your computer and use it in GitHub Desktop.
Save syfun/e443157eebb707ccc8506ba3fa861ddc to your computer and use it in GitHub Desktop.
golang gists
f, err := os.OpenFile("testlogfile", os.O_RDWR | os.O_CREATE | os.O_APPEND, 0666)
if err != nil {
t.Fatalf("error opening file: %v", err)
}
defer f.Close()
log.SetOutput(f)
log.Println("This is a test log entry")
// sched to start scheduler job at start time by interval duration.
func sched(jobFunc interface{}, start, interval string, jobArgs ...interface{}) {
jobValue := reflect.ValueOf(jobFunc)
if jobValue.Kind() != reflect.Func {
log.Panic("only function can be schedule.")
}
if len(jobArgs) != jobValue.Type().NumIn() {
log.Panic("The number of args valid.")
}
// Get job function args.
in := make([]reflect.Value, len(jobArgs))
for i, arg := range jobArgs {
in[i] = reflect.ValueOf(arg)
}
d, err := time.ParseDuration(interval)
if err != nil {
log.Panic(err)
}
location, err := time.LoadLocation("Asia/Shanghai")
if err != nil {
log.Panic(err)
}
t, err := time.ParseInLocation("15:04:05", start, location)
if err != nil {
log.Panic(err)
}
now := time.Now()
// Start time.
t = time.Date(now.Year(), now.Month(), now.Day(), t.Hour(), t.Minute(), t.Second(), 0, location)
if now.After(t) {
t = t.Add((now.Sub(t)/d + 1) * d)
}
time.Sleep(t.Sub(now))
go jobValue.Call(in)
ticker := time.NewTicker(d)
go func() {
for _ = range ticker.C {
go jobValue.Call(in)
}
}()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment