examples_test.go 1.4 KB
Newer Older
Jeromy's avatar
Jeromy committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package periodicproc_test

import (
	"fmt"
	"time"

	goprocess "QmSir6qPL1tjuxd8LkR8VZq6v625ExAUVs2eCLeqQuaPGU/goprocess"
	periodicproc "QmSir6qPL1tjuxd8LkR8VZq6v625ExAUVs2eCLeqQuaPGU/goprocess/periodic"
)

func ExampleEvery() {
	tock := make(chan struct{})

	i := 0
	p := periodicproc.Every(time.Second, func(proc goprocess.Process) {
		tock <- struct{}{}
		fmt.Printf("hello %d\n", i)
		i++
	})

	<-tock
	<-tock
	<-tock
	p.Close()

	// Output:
	// hello 0
	// hello 1
	// hello 2
}

func ExampleTick() {
	p := periodicproc.Tick(time.Second, func(proc goprocess.Process) {
		fmt.Println("tick")
	})

	<-time.After(3*time.Second + 500*time.Millisecond)
	p.Close()

	// Output:
	// tick
	// tick
	// tick
}

func ExampleTickGo() {

	// with TickGo, execution is not rate limited,
	// there can be many in-flight simultaneously

	wait := make(chan struct{})
	p := periodicproc.TickGo(time.Second, func(proc goprocess.Process) {
		fmt.Println("tick")
		<-wait
	})

	<-time.After(3*time.Second + 500*time.Millisecond)

	wait <- struct{}{}
	wait <- struct{}{}
	wait <- struct{}{}
	p.Close() // blocks us until all children are closed.

	// Output:
	// tick
	// tick
	// tick
}

func ExampleOnSignal() {
	sig := make(chan struct{})
	p := periodicproc.OnSignal(sig, func(proc goprocess.Process) {
		fmt.Println("fire!")
	})

	sig <- struct{}{}
	sig <- struct{}{}
	sig <- struct{}{}
	p.Close()

	// Output:
	// fire!
	// fire!
	// fire!
}