Created
November 6, 2021 08:56
-
-
Save Ajnasz/f0c58a9fe060311823eb15ae3f0fba88 to your computer and use it in GitHub Desktop.
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" | |
"math/rand" | |
"os" | |
"os/signal" | |
"syscall" | |
"time" | |
) | |
// schedule function calls the `fn` function after `freq` time of it's last | |
// call | |
func schedule(fn func(), freq time.Duration, stopChan chan struct{}) { | |
for { | |
select { | |
case <-time.After(freq): | |
fn() | |
case <-stopChan: | |
fmt.Println("stop") | |
stopChan <- struct{}{} | |
return | |
} | |
} | |
} | |
// task is a dummy example for a task | |
// sometimes it will take more than me.Duration to finish the task | |
func task(name string, t time.Duration) func() { | |
lastCall := time.Now() | |
return func() { | |
s := rand.Intn(int(t) + 500) | |
time.Sleep(time.Duration(s) / 1000000 * time.Millisecond) | |
now := time.Now() | |
fmt.Println("task", name, s, now.Sub(lastCall)) | |
lastCall = now | |
} | |
} | |
func main() { | |
termChan := make(chan os.Signal) | |
signal.Notify(termChan, syscall.SIGTERM, syscall.SIGINT) | |
stopChan := make(chan struct{}) | |
go func() { | |
callFreq := time.Second | |
schedule(task("A task", callFreq), callFreq, stopChan) | |
}() | |
<-termChan | |
// we use the stopChan channel to notify the scheduler that it should stop executing tasks | |
stopChan <- struct{}{} | |
// we also use the stopChan channel to get notified that the scheduler stopped | |
<-stopChan | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment