File: real.go

package info (click to toggle)
golang-github-coder-quartz 0.1.3-2
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 144 kB
  • sloc: makefile: 2
file content (80 lines) | stat: -rw-r--r-- 1,441 bytes parent folder | download
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
package quartz

import (
	"context"
	"time"
)

type realClock struct{}

func NewReal() Clock {
	return realClock{}
}

func (realClock) NewTicker(d time.Duration, _ ...string) *Ticker {
	tkr := time.NewTicker(d)
	return &Ticker{ticker: tkr, C: tkr.C}
}

func (realClock) TickerFunc(ctx context.Context, d time.Duration, f func() error, _ ...string) Waiter {
	ct := &realContextTicker{
		ctx: ctx,
		tkr: time.NewTicker(d),
		f:   f,
		err: make(chan error, 1),
	}
	go ct.run()
	return ct
}

type realContextTicker struct {
	ctx context.Context
	tkr *time.Ticker
	f   func() error
	err chan error
}

func (t *realContextTicker) Wait(_ ...string) error {
	return <-t.err
}

func (t *realContextTicker) run() {
	defer t.tkr.Stop()
	for {
		select {
		case <-t.ctx.Done():
			t.err <- t.ctx.Err()
			return
		case <-t.tkr.C:
			err := t.f()
			if err != nil {
				t.err <- err
				return
			}
		}
	}
}

func (realClock) NewTimer(d time.Duration, _ ...string) *Timer {
	rt := time.NewTimer(d)
	return &Timer{C: rt.C, timer: rt}
}

func (realClock) AfterFunc(d time.Duration, f func(), _ ...string) *Timer {
	rt := time.AfterFunc(d, f)
	return &Timer{C: rt.C, timer: rt}
}

func (realClock) Now(_ ...string) time.Time {
	return time.Now()
}

func (realClock) Since(t time.Time, _ ...string) time.Duration {
	return time.Since(t)
}

func (realClock) Until(t time.Time, _ ...string) time.Duration {
	return time.Until(t)
}

var _ Clock = realClock{}