Last active
July 20, 2022 06:00
-
-
Save sivsivsree/d731e58c30379f11a7d70a4ef163d9bd to your computer and use it in GitHub Desktop.
This file contains hidden or 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 ( | |
"context" | |
"fmt" | |
"os" | |
"os/signal" | |
"syscall" | |
"time" | |
) | |
func main() { | |
ctx, cancel := context.WithCancel(context.Background()) | |
defer cancel() | |
exit := make(chan os.Signal, 1) | |
signal.Notify(exit, os.Interrupt, syscall.SIGTERM) | |
go longBackgroundWorker(ctx) | |
<-exit | |
cancel() | |
// the sleep to show the ctx std output before exiting immediately. | |
time.Sleep(1 * time.Second) | |
} | |
// longBackgroundWorker is an example function to demonstrate | |
// the context cancel listen event. | |
func longBackgroundWorker(ctx context.Context) { | |
// a ticker is created for simulating a continuous process. | |
ticker := time.NewTicker(1 * time.Second) | |
for { | |
select { | |
case <-ticker.C: | |
// This can be a file streaming service, | |
// database transactions etc. | |
fmt.Println("I am a long running process") | |
case <-ctx.Done(): | |
// you could cancel or save the checkpoint | |
// of the long-running process in this scenario. | |
fmt.Println("Canceling the last running process.") | |
ticker.Stop() | |
return | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment