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

108 lines
1.8 KiB
Go

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package startimer
import (
"context"
"sync"
"time"
)
type Unit uint8
const (
STAR_SECOND Unit = iota
STAR_MINUTE
STAR_HOUR
STAR_DAY
STAR_MONTH
STAR_WEEK
STAR_YEAR
)
type Repeats struct {
Repeat []Repeat `json:"repeat"`
Every bool `json:"every"` // false=static true=every
}
type Repeat struct {
Unit Unit `json:"unit"`
baseDate time.Time
Value uint32 `json:"value"`
}
type StarTimer struct {
base time.Time
nextDate time.Time
timer *time.Timer
stopFn context.CancelFunc
stopCtx context.Context
mu *sync.RWMutex
running bool
runCount int
runLimit int
repeat []*Repeats
tasks []func()
//staticMode 意味永久以当前时间为基准进行动作例如crontab
staticMode bool
}
type TimerOptions func(option *TimerOption)
type TimerOption struct {
idx uint8
repeats *Repeats
tasks func()
date time.Time
repeat Repeat
runLimit int
}
func WithRunCountLimit(rm int) TimerOptions {
return func(option *TimerOption) {
option.runLimit = rm
}
}
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
}
}
func NewRepeat(baseTime time.Time, unit Unit, val uint32) Repeat {
return Repeat{
Unit: unit,
baseDate: baseTime,
Value: val,
}
}
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))
}