Skip to content

Instantly share code, notes, and snippets.

@pioh
Created June 26, 2023 18:06
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 pioh/789bcec39e293fc792aa8b256329918f to your computer and use it in GitHub Desktop.
Save pioh/789bcec39e293fc792aa8b256329918f to your computer and use it in GitHub Desktop.
task runner
package main
import (
"fmt"
"log"
"net/http"
"strconv"
"time"
)
func main() {
http.HandleFunc("/task", func(w http.ResponseWriter, r *http.Request) {
if err := handler(r); err != nil {
w.WriteHeader(500)
_, _ = w.Write([]byte(err.Error()))
return
}
w.WriteHeader(200)
})
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal(err)
}
}
func handler(r *http.Request) error {
q := r.URL.Query()
message := q.Get("message")
duration, err := strconv.Atoi(q.Get("duration"))
if err != nil {
return fmt.Errorf("duration: %w", err)
}
delay, err := strconv.Atoi(q.Get("delay"))
if err != nil {
return fmt.Errorf("delay: %w", err)
}
time.AfterFunc(time.Duration(delay)*time.Second, func() {
task(message, time.Duration(duration)*time.Second)
})
return nil
}
func task(message string, duration time.Duration) {
log.Printf("task %v started", message)
time.Sleep(duration)
log.Printf("task %v finished", message)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment