|
| 1 | +// Copyright 2022 The Go Authors. All rights reserved. |
| 2 | +// Use of this source code is governed by a BSD-style |
| 3 | +// license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +package rate_test |
| 6 | + |
| 7 | +import ( |
| 8 | + "fmt" |
| 9 | + "math" |
| 10 | + "testing" |
| 11 | + "time" |
| 12 | + |
| 13 | + "golang.org/x/time/rate" |
| 14 | +) |
| 15 | + |
| 16 | +func ExampleSometimes_once() { |
| 17 | + // The zero value of Sometimes behaves like sync.Once, though less efficiently. |
| 18 | + var s rate.Sometimes |
| 19 | + s.Do(func() { fmt.Println("1") }) |
| 20 | + s.Do(func() { fmt.Println("2") }) |
| 21 | + s.Do(func() { fmt.Println("3") }) |
| 22 | + // Output: |
| 23 | + // 1 |
| 24 | +} |
| 25 | + |
| 26 | +func ExampleSometimes_first() { |
| 27 | + s := rate.Sometimes{First: 2} |
| 28 | + s.Do(func() { fmt.Println("1") }) |
| 29 | + s.Do(func() { fmt.Println("2") }) |
| 30 | + s.Do(func() { fmt.Println("3") }) |
| 31 | + // Output: |
| 32 | + // 1 |
| 33 | + // 2 |
| 34 | +} |
| 35 | + |
| 36 | +func ExampleSometimes_every() { |
| 37 | + s := rate.Sometimes{Every: 2} |
| 38 | + s.Do(func() { fmt.Println("1") }) |
| 39 | + s.Do(func() { fmt.Println("2") }) |
| 40 | + s.Do(func() { fmt.Println("3") }) |
| 41 | + // Output: |
| 42 | + // 1 |
| 43 | + // 3 |
| 44 | +} |
| 45 | + |
| 46 | +func ExampleSometimes_interval() { |
| 47 | + s := rate.Sometimes{Interval: 1 * time.Second} |
| 48 | + s.Do(func() { fmt.Println("1") }) |
| 49 | + s.Do(func() { fmt.Println("2") }) |
| 50 | + time.Sleep(1 * time.Second) |
| 51 | + s.Do(func() { fmt.Println("3") }) |
| 52 | + // Output: |
| 53 | + // 1 |
| 54 | + // 3 |
| 55 | +} |
| 56 | + |
| 57 | +func ExampleSometimes_mix() { |
| 58 | + s := rate.Sometimes{ |
| 59 | + First: 2, |
| 60 | + Every: 2, |
| 61 | + Interval: 2 * time.Second, |
| 62 | + } |
| 63 | + s.Do(func() { fmt.Println("1 (First:2)") }) |
| 64 | + s.Do(func() { fmt.Println("2 (First:2)") }) |
| 65 | + s.Do(func() { fmt.Println("3 (Every:2)") }) |
| 66 | + time.Sleep(2 * time.Second) |
| 67 | + s.Do(func() { fmt.Println("4 (Interval)") }) |
| 68 | + s.Do(func() { fmt.Println("5 (Every:2)") }) |
| 69 | + s.Do(func() { fmt.Println("6") }) |
| 70 | + // Output: |
| 71 | + // 1 (First:2) |
| 72 | + // 2 (First:2) |
| 73 | + // 3 (Every:2) |
| 74 | + // 4 (Interval) |
| 75 | + // 5 (Every:2) |
| 76 | +} |
| 77 | + |
| 78 | +func TestSometimesZero(t *testing.T) { |
| 79 | + s := rate.Sometimes{Interval: 0} |
| 80 | + s.Do(func() {}) |
| 81 | + s.Do(func() {}) |
| 82 | +} |
| 83 | + |
| 84 | +func TestSometimesMax(t *testing.T) { |
| 85 | + s := rate.Sometimes{Interval: math.MaxInt64} |
| 86 | + s.Do(func() {}) |
| 87 | + s.Do(func() {}) |
| 88 | +} |
| 89 | + |
| 90 | +func TestSometimesNegative(t *testing.T) { |
| 91 | + s := rate.Sometimes{Interval: -1} |
| 92 | + s.Do(func() {}) |
| 93 | + s.Do(func() {}) |
| 94 | +} |
0 commit comments