schedule.go 820 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. // Copyright 2016 Martin Hebnes Pedersen (LA5NTA). All rights reserved.
  2. // Use of this source code is governed by the MIT-license that can be
  3. // found in the LICENSE file.
  4. package main
  5. import (
  6. "github.com/gorhill/cronexpr"
  7. "log"
  8. "time"
  9. )
  10. type Job struct {
  11. expr *cronexpr.Expression
  12. cmd string
  13. next time.Time
  14. }
  15. func scheduleLoop() {
  16. jobs := make([]*Job, 0, len(config.Schedule))
  17. for exprStr, cmd := range config.Schedule {
  18. expr := cronexpr.MustParse(exprStr)
  19. jobs = append(jobs, &Job{
  20. expr,
  21. cmd,
  22. expr.Next(time.Now()),
  23. })
  24. }
  25. go func() {
  26. for range time.Tick(time.Second) {
  27. for _, j := range jobs {
  28. if time.Now().Before(j.next) {
  29. continue
  30. }
  31. log.Printf("Executing scheduled command '%s'...", j.cmd)
  32. execCmd(j.cmd)
  33. j.next = j.expr.Next(time.Now())
  34. }
  35. }
  36. }()
  37. }