Skip to content

Commit

Permalink
fix issue #72: add example with context
Browse files Browse the repository at this point in the history
  • Loading branch information
kamilsk committed Nov 30, 2017
1 parent 9fa837e commit d9a2e6b
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,27 @@ $ retry --infinite -timeout 10m -backoff=lin:500ms -- /bin/sh -c 'echo "trying..

See more details [here](cmd/retry).

### Use context for cancellation

This example shows how to use context and retry together.

```go
communication := make(chan error)

go service.Listen(communication)

action := func(uint) error {
communication <- nil // ping
return <-communication // pong
}
ctx := retry.WithContext(context.Background(), retry.WithTimeout(time.Second))
if err := retry.Retry(ctx.Done(), action, strategy.Delay(time.Millisecond)); err != nil {
// the service does not respond within one second
}
```

See more details [here](https://godoc.org/github.com/kamilsk/retry#example-package--RetryWithContext).

### Interrupt execution

```go
Expand Down
44 changes: 44 additions & 0 deletions example_retry_with_context_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// +build go1.7

package retry_test

import (
"context"
"errors"
"fmt"
"time"

"github.com/kamilsk/retry"
"github.com/kamilsk/retry/strategy"
)

// This example shows how to use context and retry together.
func Example_retryWithContext() {
const expected = 3

attempts := 3
communication := make(chan error)
go func() {
for {
<-communication
if attempts == 0 {
close(communication)
return
}
attempts--
communication <- errors.New("service unavailable")
}
}()

action := func(uint) error {
communication <- nil // ping
return <-communication // pong
}
ctx := retry.WithContext(context.Background(), retry.WithTimeout(time.Second))
if err := retry.Retry(ctx.Done(), action, strategy.Delay(time.Millisecond)); err != nil {
panic(err)
}

fmt.Printf("attempts: %d, expected: %d \n", expected-attempts, expected)
// Output: attempts: 3, expected: 3
}

0 comments on commit d9a2e6b

Please sign in to comment.