-
Notifications
You must be signed in to change notification settings - Fork 1
/
period.go
44 lines (34 loc) · 854 Bytes
/
period.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
package timeperiod
import (
"time"
"github.com/gorhill/cronexpr"
)
type TimePeriod struct {
expressions []*cronexpr.Expression
GetCurrentTime func() time.Time
}
func (t *TimePeriod) InPeriod() bool {
for _, expression := range t.expressions {
nextIn := expression.Next(t.GetCurrentTime())
timeSince := time.Since(nextIn)
if timeSince < time.Second && timeSince > -time.Second {
return true
}
}
return false
}
func TimePeriods(periods []string) (*TimePeriod, error) {
var expressions []*cronexpr.Expression
for _, period := range periods {
expression, err := cronexpr.Parse(period)
if err != nil {
return nil, err
}
expressions = append(expressions, expression)
}
timePeriod := &TimePeriod{
expressions: expressions,
GetCurrentTime: func() time.Time { return time.Now() },
}
return timePeriod, nil
}