aboutsummaryrefslogtreecommitdiff
path: root/bus_test.go
blob: ca3a6649e78b4e3dfebcc7f9a876b656575030b7 (plain) (blame)
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
package fqueue_test

import (
	"context"
	"fmt"
	"os"
	"strconv"
	"time"

	"go.neonxp.ru/fqueue"
)

func Example() {
	tasksDir, err := os.MkdirTemp(os.TempDir(), "tasks_*")
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(tasksDir)

	bus, err := fqueue.New(tasksDir)
	if err != nil {
		panic(err)
	}

	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()

	for i := range 5 {
		t := Task("Task #" + strconv.Itoa(i))
		id, err := bus.Publish(ctx, t.Encode())
		if err != nil {
			panic(err)
		}
		fmt.Println("Task id=", id, "published with text", t)
	}

	for t, err := range bus.NextTask(ctx) {
		if err != nil {
			panic(err)
		}
		fmt.Println("Got task", string(t))
	}
	// Output:
	// Task id= 1 published with text Task #0
	// Task id= 2 published with text Task #1
	// Task id= 3 published with text Task #2
	// Task id= 4 published with text Task #3
	// Task id= 5 published with text Task #4
	// Got task Task #0
	// Got task Task #1
	// Got task Task #2
	// Got task Task #3
	// Got task Task #4
}

type Task string

func (t Task) Encode() []byte {
	return []byte(t)
}