You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
startimer/typed.go

97 lines
1.6 KiB
Go

2 years ago
package startimer
import (
"context"
"sync"
"time"
)
type Unit uint8
const (
STAR_SECOND Unit = iota
STAR_MINUTE
STAR_HOUR
STAR_DAY
STAR_MONTH
2 years ago
STAR_WEEK
2 years ago
STAR_YEAR
2 years ago
)
type Repeats struct {
2 years ago
Repeat []Repeat `json:"repeat"`
Every bool `json:"every"` // false=static true=every
2 years ago
}
type Repeat struct {
2 years ago
Unit Unit `json:"unit"`
2 years ago
baseDate time.Time
2 years ago
Value uint32 `json:"value"`
2 years ago
}
type StarTimer struct {
base time.Time
nextDate time.Time
timer *time.Timer
stopFn context.CancelFunc
stopCtx context.Context
mu *sync.RWMutex
running bool
repeat []*Repeats
tasks []func()
}
type TimerOptions func(option *TimerOption)
type TimerOption struct {
idx uint8
repeats *Repeats
tasks func()
2 years ago
date time.Time
repeat Repeat
2 years ago
}
func WithRepeats(r *Repeats) TimerOptions {
return func(option *TimerOption) {
option.idx = 1
option.repeats = r
}
}
func WithRepeat(r Repeat) TimerOptions {
return func(option *TimerOption) {
option.idx = 4
option.repeat = r
}
}
func WithTask(t func()) TimerOptions {
return func(option *TimerOption) {
option.idx = 2
option.tasks = t
}
}
func WithStaticDate(t time.Time) TimerOptions {
return func(option *TimerOption) {
option.idx = 3
option.date = t
}
}
2 years ago
func NewRepeat(baseTime time.Time, unit Unit, val uint32) Repeat {
return Repeat{
Unit: unit,
baseDate: baseTime,
Value: val,
}
}
2 years ago
func NextDayOfWeek(date time.Time, weekDay int) time.Time {
sub := weekDay - int(date.Weekday())
if sub <= 0 {
sub += 7
}
return date.Add(time.Hour * 24 * time.Duration(sub))
}