Last active
May 11, 2024 09:14
-
-
Save dipankardas011/c9db044b1d23cac911b482237de54346 to your computer and use it in GitHub Desktop.
go time ticker and context timeout
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 ( | |
"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