Created
March 16, 2023 01:30
-
-
Save escoffier/97e8560905854f7ccb4d44e38bdda08e 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 := cancelCtxOnSigterm(context.Background()) | |
startWork(ctx) | |
} | |
// cancelCtxOnSigterm returns a Context that will be cancelled when the program receives a sigterm. | |
func cancelCtxOnSigterm(ctx context.Context) context.Context { | |
exitCh := make(chan os.Signal, 1) | |
signal.Notify(exitCh, os.Interrupt, syscall.SIGTERM) | |
ctx, cancel := context.WithCancel(ctx) | |
go func() { | |
<-exitCh | |
cancel() | |
}() | |
return ctx | |
} | |
// startWork performs a task every 60 seconds until the context is done. | |
func startWork(ctx context.Context) { | |
ticker := time.NewTicker(60 * time.Second) | |
defer ticker.Stop() | |
for { | |
// Do work here so we don't need duplicate calls. It will run immediately, and again every minute as the loop continues. | |
if err := work(ctx); err != nil { | |
fmt.Printf("failed to do work: %s", err) | |
} | |
select { | |
case <-ticker.C: | |
continue | |
case <-ctx.Done(): | |
return | |
} | |
} | |
} | |
func work(ctx context.Context) error { | |
fmt.Println("doing work") | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment