Created
June 26, 2023 18:06
-
-
Save pioh/789bcec39e293fc792aa8b256329918f to your computer and use it in GitHub Desktop.
task runner
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" | |
"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