I want to create a scheduler so that it executes a task every second for example, but also would like to have and http interface to stop/start the scheduler and get more stats/info, after reading more about timers & tickers, channels and gorutines I came out with this:
https://gist.github.com/nbari/483c5b382c795bf290b5
package main
import (
"fmt"
"log"
"net/http"
"time"
)
var timer *time.Ticker
func scheduler(seconds time.Duration) *time.Ticker {
ticker := time.NewTicker(seconds * time.Second)
go func() {
for t := range ticker.C {
// do stuff
fmt.Println(t)
}
}()
return ticker
}
func Start(timer *time.Ticker) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
timer = scheduler(1)
w.Write([]byte("Starting scheduler"))
})
}
func Stop(timer *time.Ticker) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
timer.Stop()
w.Write([]byte("Stoping scheduler"))
})
}
func main() {
timer = scheduler(1)
http.Handle("/start", Start(timer))
http.Handle("/stop", Stop(timer))
log.Fatal(http.ListenAndServe(":8080", nil))
}
The above code is working but I have a global "timer" variable, I would like to know if there is a better way to implement this and also a way for handle more than 1 scheduler, currently thinking on probably implementing kind of a container for all the scheduler but would like to have some feedbacks that could help me find clever solutions.