forked from gocelery/gocelery
-
Notifications
You must be signed in to change notification settings - Fork 1
/
example_worker_named_arg_test.go
79 lines (66 loc) · 1.54 KB
/
example_worker_named_arg_test.go
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
// Copyright (c) 2019 Sick Yoon
// This file is part of gocelery which is released under MIT license.
// See file LICENSE for full license details.
package gocelery
import (
"fmt"
"time"
"github.com/gomodule/redigo/redis"
)
// exampleAddTask is integer addition task
// with named arguments
type exampleAddTask struct {
a int
b int
}
func (a *exampleAddTask) ParseKwargs(kwargs map[string]interface{}) error {
kwargA, ok := kwargs["a"]
if !ok {
return fmt.Errorf("undefined kwarg a")
}
kwargAFloat, ok := kwargA.(float64)
if !ok {
return fmt.Errorf("malformed kwarg a")
}
a.a = int(kwargAFloat)
kwargB, ok := kwargs["b"]
if !ok {
return fmt.Errorf("undefined kwarg b")
}
kwargBFloat, ok := kwargB.(float64)
if !ok {
return fmt.Errorf("malformed kwarg b")
}
a.b = int(kwargBFloat)
return nil
}
func (a *exampleAddTask) RunTask() (interface{}, error) {
result := a.a + a.b
return result, nil
}
func Example_workerWithNamedArguments() {
// create redis connection pool
redisPool := &redis.Pool{
Dial: func() (redis.Conn, error) {
c, err := redis.DialURL("redis://")
if err != nil {
return nil, err
}
return c, err
},
}
// initialize celery client
cli, _ := NewCeleryClient(
NewRedisBroker(redisPool),
&RedisCeleryBackend{Pool: redisPool},
5, // number of workers
)
// register task
cli.Register("add", &exampleAddTask{})
// start workers (non-blocking call)
cli.StartWorker()
// wait for client request
time.Sleep(10 * time.Second)
// stop workers gracefully (blocking call)
cli.StopWorker()
}