File: period.go

package info (click to toggle)
gitlab-ci-multi-runner 14.10.1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 31,248 kB
  • sloc: sh: 1,694; makefile: 384; asm: 79; ruby: 68
file content (60 lines) | stat: -rw-r--r-- 1,298 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
package timeperiod

import (
	"time"

	"github.com/gorhill/cronexpr"
)

type TimePeriod struct {
	expressions    []*cronexpr.Expression
	location       *time.Location
	GetCurrentTime func() time.Time
}

func (t *TimePeriod) InPeriod() bool {
	now := t.GetCurrentTime().In(t.location)
	for _, expression := range t.expressions {
		nextIn := expression.Next(now)
		timeSince := now.Sub(nextIn)
		if -time.Second <= timeSince && timeSince <= time.Second {
			return true
		}
	}

	return false
}

func TimePeriods(periods []string, timezone string) (*TimePeriod, error) {
	return TimePeriodsWithTimer(periods, timezone, time.Now)
}

func TimePeriodsWithTimer(periods []string, timezone string, timer func() time.Time) (*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)
	}

	// if not set, default to system setting (the empty string would mean UTC)
	if timezone == "" {
		timezone = "Local"
	}
	location, err := time.LoadLocation(timezone)
	if err != nil {
		return nil, err
	}

	timePeriod := &TimePeriod{
		expressions:    expressions,
		location:       location,
		GetCurrentTime: timer,
	}

	return timePeriod, nil
}