Skip to content

Instantly share code, notes, and snippets.

@kevinschoon
Last active November 20, 2015 00:45
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 kevinschoon/239a0dbbb38172f15edb to your computer and use it in GitHub Desktop.
Save kevinschoon/239a0dbbb38172f15edb to your computer and use it in GitHub Desktop.
Random Cron Scheduler
package main
import (
"fmt"
"time"
"math/rand"
"bytes"
"gopkg.in/robfig/cron.v2"
)
func PrintTheTime(name string) {
fmt.Printf("I am %s and the time is %s\n", name, time.Now())
}
func randomNumber(min, max int) (int) {
rand.Seed(time.Now().UTC().UnixNano())
i := rand.Intn(max-min) + min
return i
}
func listOfNumbers(min, max, count int) string {
var buffer bytes.Buffer
for i := 0; i < count; i++ {
if count > 1 {
if i != 0 {
buffer.WriteString(fmt.Sprintf(","))
}
}
buffer.WriteString(fmt.Sprintf("%d", randomNumber(min, max)))
}
s := buffer.String()
return s
}
func GetSpec(duration int) string {
var spec string
switch {
case duration == 1:
spec = fmt.Sprintf("%s * * * * *", listOfNumbers(1, 59, 1))
case duration == 5:
spec = fmt.Sprintf("%s %s * * * *", listOfNumbers(1, 59, 1), listOfNumbers(1, 59, 12))
case duration == 15:
spec = fmt.Sprintf("%s %s * * * *", listOfNumbers(1, 59, 1), listOfNumbers(1, 59, 4))
case duration == 30:
spec = fmt.Sprintf("%s %s * * * *", listOfNumbers(1, 59, 1), listOfNumbers(1, 59, 2))
case duration == 60:
spec = fmt.Sprintf("%s %s * * * *", listOfNumbers(1, 59, 1), listOfNumbers(1, 59, 1))
}
return spec
}
func main() {
c := cron.New()
c.Start()
for i := 0; i < 500; i++ {
spec := GetSpec(5)
fmt.Printf("%s\n", spec)
c.AddFunc(spec, func() {PrintTheTime(spec)})
}
select{}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment