Skip to content

Instantly share code, notes, and snippets.

@dipankardas011
Last active May 11, 2024 09:14
Show Gist options
  • Save dipankardas011/c9db044b1d23cac911b482237de54346 to your computer and use it in GitHub Desktop.
Save dipankardas011/c9db044b1d23cac911b482237de54346 to your computer and use it in GitHub Desktop.
go time ticker and context timeout
package main
import (
"context"
"fmt"
"os"
"os/signal"
"syscall"
"time"
)
func main() {
maxTime := 10 * time.Second
jobTime := 15 * time.Second
ctx, cancel := context.WithTimeout(context.Background(), maxTime)
ctx, cancel = signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM)
defer func() {
func() {
println("Cleanup [aka checking if any thing is left]")
}()
cancel()
}()
result, err := dummry(ctx, jobTime)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("return: %d\n", result)
return
}
// simulating some work
func dummry(ctx context.Context, t time.Duration) (int, error) {
ticker := time.NewTimer(t)
for {
select {
case <-ticker.C:
return 0, nil
case <-ctx.Done():
return 0, ctx.Err()
default:
fmt.Println(time.Now(), "Waiting for timer to go off")
time.Sleep(time.Second)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment