| 1 |
package deadline |
| 2 |
|
| 3 |
import ( |
| 4 |
"errors" |
| 5 |
"testing" |
| 6 |
"time" |
| 7 |
) |
| 8 |
|
| 9 |
func takesFiveMillis(stopper <-chan struct{}) error { |
| 10 |
time.Sleep(5 * time.Millisecond) |
| 11 |
return nil |
| 12 |
} |
| 13 |
|
| 14 |
func takesTwentyMillis(stopper <-chan struct{}) error { |
| 15 |
time.Sleep(20 * time.Millisecond) |
| 16 |
return nil |
| 17 |
} |
| 18 |
|
| 19 |
func returnsError(stopper <-chan struct{}) error { |
| 20 |
return errors.New("foo") |
| 21 |
} |
| 22 |
|
| 23 |
func TestDeadline(t *testing.T) { |
| 24 |
dl := New(10 * time.Millisecond) |
| 25 |
|
| 26 |
if err := dl.Run(takesFiveMillis); err != nil { |
| 27 |
t.Error(err) |
| 28 |
} |
| 29 |
|
| 30 |
if err := dl.Run(takesTwentyMillis); err != ErrTimedOut { |
| 31 |
t.Error(err) |
| 32 |
} |
| 33 |
|
| 34 |
if err := dl.Run(returnsError); err.Error() != "foo" { |
| 35 |
t.Error(err) |
| 36 |
} |
| 37 |
|
| 38 |
done := make(chan struct{}) |
| 39 |
err := dl.Run(func(stopper <-chan struct{}) error { |
| 40 |
<-stopper |
| 41 |
close(done) |
| 42 |
return nil |
| 43 |
}) |
| 44 |
if err != ErrTimedOut { |
| 45 |
t.Error(err) |
| 46 |
} |
| 47 |
<-done |
| 48 |
} |
| 49 |
|
| 50 |
func ExampleDeadline() { |
| 51 |
dl := New(1 * time.Second) |
| 52 |
|
| 53 |
err := dl.Run(func(stopper <-chan struct{}) error { |
| 54 |
// do something possibly slow |
| 55 |
// check stopper function and give up if timed out |
| 56 |
return nil |
| 57 |
}) |
| 58 |
|
| 59 |
switch err { |
| 60 |
case ErrTimedOut: |
| 61 |
// execution took too long, oops |
| 62 |
default: |
| 63 |
// some other error |
| 64 |
} |
| 65 |
} |