-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkeepalive.go
60 lines (51 loc) · 1.55 KB
/
keepalive.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
package sqlq
import (
"context"
"database/sql"
"github.com/pkg/errors"
"time"
)
type Pinger interface {
Ping(context.Context) error
}
type pingFunc func(context.Context) error
func (fn pingFunc) Ping(ctx context.Context) error { return fn(ctx) }
// make a ping function for the given job
func pingFn(cx Connection, job *Job) Pinger {
return pingFunc(func(ctx context.Context) (err error) {
const ping = `UPDATE sqlq.jobs SET last_keepalive = NOW() WHERE id = $1 AND status = $2 RETURNING *`
var rows *sql.Rows
if rows, err = cx.QueryContext(ctx, ping, job.ID, job.Status); err != nil {
return errors.Wrapf(err, "failed to send ping")
}
if err = scanJob(rows, job); err != nil {
if err == sql.ErrNoRows { // job wasn't in the given state?
return errors.Wrapf(ErrJobStateMismatch, "expected job to be in %s", job.Status)
}
return errors.Wrap(err, "failed to send ping")
}
return nil
})
}
// SendKeepAlive is a utility method that sends periodic keep-alive pings, every d duration.
//
// This function starts an infinite for-loop that periodically sends ping using job.Pinger().
// Call this function in a background goroutine, like:
//
// go job.SendKeepAlive(ctx, job.KeepAlive)
//
// To stop sending pings, cancel the context and the function will return.
func (job *Job) SendKeepAlive(ctx context.Context, d time.Duration) error {
var ticker = time.NewTicker(d)
for {
select {
case <-ctx.Done():
ticker.Stop()
return ctx.Err()
case <-ticker.C:
if err := job.Pinger().Ping(ctx); err != nil {
return err
}
}
}
}