Last active
November 20, 2015 00:45
-
-
Save kevinschoon/239a0dbbb38172f15edb to your computer and use it in GitHub Desktop.
Random Cron Scheduler
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 ( | |
"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