Skip to content

Instantly share code, notes, and snippets.

@escoffier
Created March 16, 2023 01:30
Show Gist options
  • Save escoffier/97e8560905854f7ccb4d44e38bdda08e to your computer and use it in GitHub Desktop.
Save escoffier/97e8560905854f7ccb4d44e38bdda08e to your computer and use it in GitHub Desktop.
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