Documentation
¶
Overview ¶
文件:cronexpr.go Purpose: Cron expression public API: Parse / MustParse and generic helpers. 来源:移植自第三方开源项目 gorhill/cronexpr(MIT License),仅做最小化适配:
- 去除对 robinlindsley/go-pkgs 的依赖,改为标准库实现;
- 保持表达式语义不变,支持 5~7 个字段(秒 分 时 日 月 周 [年])。
说明:cron 相关文件为第三方实现,不做逐行注释,仅补充文件级说明。 Note: cron files are vendored from a third-party project; only file-level documentation is added instead of line-by-line comments.
文件:cronexpr_next.go Purpose: Compute the next activation time of a parsed Expression (year -> month -> day -> hour -> minute -> second cascade). 来源:移植自 gorhill/cronexpr(MIT License),仅做最小化适配,未匹配语义。 Source: adapted from gorhill/cronexpr (MIT License) with minimal changes.
文件:cronexpr_parse.go Purpose: Cron expression parsing: field splitting, range/step/last/weekday expansion into the internal bit lists used by cronexpr_next.go. 来源:移植自 gorhill/cronexpr(MIT License),仅做最小化适配,未修改解析语义。 Source: adapted from gorhill/cronexpr (MIT License) with minimal changes.
Package scheduler 是一个基于层级时间轮的定时任务调度器,支持任务持久化与自定义触发器。 Package scheduler is a cron-style job scheduler built on a hierarchical timing wheel, with optional database persistence and pluggable custom triggers.
Index ¶
- Constants
- func RegisterTrigger(name string, proto Trigger) error
- type Args
- type ConcurrencyPolicy
- type CronTrigger
- type DateTrigger
- type DelayQueue
- type Expression
- type IntervalTrigger
- type Options
- type PeriodicTask
- type SafeMapOfInt
- type Scheduler
- func (s *Scheduler) ActiveCount() int
- func (s *Scheduler) AddTask(key string, p PeriodicTask) error
- func (s *Scheduler) AddTaskFunction(structs ...interface{})
- func (s *Scheduler) ContinueTask(key string) error
- func (s *Scheduler) InitFromDB()
- func (s *Scheduler) MaxConcurrency() int
- func (s *Scheduler) Mode() string
- func (s *Scheduler) PendingCount() int
- func (s *Scheduler) RemoveTask(key string) error
- func (s *Scheduler) ResetTask(key string, p PeriodicTask) error
- func (s *Scheduler) SetMaxConcurrency(n int)
- func (s *Scheduler) Start()
- func (s *Scheduler) StartTaskNow(key string) error
- func (s *Scheduler) Stats() Stats
- func (s *Scheduler) Stop()
- func (s *Scheduler) StopTask(key string) error
- type Stats
- type StorageMode
- type Timer
- type TimingWheel
- type Trigger
Constants ¶
const ( Date = "date" // 单次任务 / one-shot job Interval = "interval" // 固定间隔 / fixed interval Cron = "cron" // cron 表达式 / cron expression )
内置触发器类型名 / Built-in trigger type names.
Variables ¶
This section is empty.
Functions ¶
func RegisterTrigger ¶
RegisterTrigger 注册自定义触发器类型,PeriodicTask.TriggerType 填同名即可使用; 服务重启后从数据库恢复任务时按此名查找原型并重建。 proto 只需零值原型(其 Build 方法负责产出真实例),重复注册返回错误。
RegisterTrigger registers a custom trigger type. proto only needs to be a zero-value prototype; its Build method produces the real instance.
Types ¶
type Args ¶
type Args []interface{}
Args 为任务调用参数,以 JSON 形式存入数据库。 Args holds the job arguments and is persisted as JSON.
type ConcurrencyPolicy ¶
type ConcurrencyPolicy int
ConcurrencyPolicy 决定达到全局并发上限时的行为。 ConcurrencyPolicy defines what happens when the concurrency limit is reached.
const ( // ConcurrencyBlock 等待空闲名额(默认):任务排队,不会丢失。 // ConcurrencyBlock waits for a free slot (default); jobs queue instead of being lost. ConcurrencyBlock ConcurrencyPolicy = iota // ConcurrencySkip 直接跳过本次执行:适合允许丢弃的轮询类任务。 // ConcurrencySkip drops the run; suitable for polling jobs that may be skipped. ConcurrencySkip )
type CronTrigger ¶
type CronTrigger struct {
Cron string
StartTime time.Time
EndTime time.Time // 零值表示不限 / zero means no end
}
CronTrigger 定义计划任务:按 cron 表达式循环执行。 CronTrigger fires according to a cron expression.
func (*CronTrigger) Build ¶
func (t *CronTrigger) Build(p PeriodicTask) (Trigger, error)
Build 校验 cron 表达式非空并构造实例。 Validates that the cron expression is present and builds an instance.
func (*CronTrigger) Next ¶
func (t *CronTrigger) Next(prev time.Time) time.Time
Next 求出下一次匹配 cron 表达式的时间;表达式为空、越过 EndTime 或解析失败时返回零值。 Returns the next matching time, or the zero time on empty expression, passed EndTime or parse failure.
func (*CronTrigger) Type ¶
func (t *CronTrigger) Type() string
Type 返回内置类型名。Returns the built-in type name.
type DateTrigger ¶
DateTrigger 定义单次任务:到期执行一次后任务终止。 DateTrigger fires once at StartTime (immediately if already past).
func (*DateTrigger) Build ¶
func (t *DateTrigger) Build(p PeriodicTask) (Trigger, error)
Build 由任务的 StartTime 构造实例。Builds an instance from the job.
func (*DateTrigger) Next ¶
func (t *DateTrigger) Next(prev time.Time) time.Time
Next 起始时间已过则立即执行,否则等待到起始时刻。 Fires immediately when StartTime is in the past.
func (*DateTrigger) Type ¶
func (t *DateTrigger) Type() string
Type 返回内置类型名。Returns the built-in type name.
type DelayQueue ¶
type DelayQueue struct {
C chan interface{} // 到期元素输出通道 / channel delivering expired elements
// contains filtered or unexported fields
}
DelayQueue 为无界阻塞延迟队列,元素到期后才能取出,队首是最早到期者。 DelayQueue is an unbounded blocking queue whose elements can only be taken once their delay has expired; the head expired furthest in the past.
func New ¶
func New(size int) *DelayQueue
New 创建延迟队列,size 为堆初始容量。 Creates a delay queue with the given initial heap capacity.
func (*DelayQueue) Offer ¶
func (dq *DelayQueue) Offer(elem interface{}, expiration int64)
Offer 按到期时间插入元素;若成为队首则唤醒 Poll。 Inserts an element by expiration time and wakes Poll when it becomes the head.
func (*DelayQueue) Poll ¶
func (dq *DelayQueue) Poll(exitC chan struct{}, nowF func() int64)
Poll 循环等待元素到期并发送到 C;exitC 关闭时退出。 Loopingly waits for elements to expire and sends them to C; exits when exitC closes.
type Expression ¶
type Expression struct {
// contains filtered or unexported fields
}
Expression 表示一个已解析的 cron 时间表达式。 Expression represents a parsed cron time expression.
func MustParse ¶
func MustParse(cronLine string) *Expression
MustParse returns a new Expression pointer. It expects a well-formed cron expression. If a malformed cron expression is supplied, it will `panic`. See <https://github.com/gorhill/cronexpr#implementation> for documentation about what is a well-formed cron expression from this library's point of view.
func Parse ¶
func Parse(cronLine string) (*Expression, error)
Parse returns a new Expression pointer. An error is returned if a malformed cron expression is supplied. See <https://github.com/gorhill/cronexpr#implementation> for documentation about what is a well-formed cron expression from this library's point of view.
func (*Expression) Next ¶
func (expr *Expression) Next(fromTime time.Time) time.Time
Next returns the closest time instant immediately following `fromTime` which matches the cron expression `expr`.
The `time.Location` of the returned time instant is the same as that of `fromTime`.
The zero value of time.Time is returned if no matching time instant exists or if a `fromTime` is itself a zero value.
func (*Expression) NextN ¶
NextN returns a slice of `n` closest time instants immediately following `fromTime` which match the cron expression `expr`.
The time instants in the returned slice are in chronological ascending order. The `time.Location` of the returned time instants is the same as that of `fromTime`.
A slice with len between [0-`n`] is returned, that is, if not enough existing matching time instants exist, the number of returned entries will be less than `n`.
type IntervalTrigger ¶
type IntervalTrigger struct {
Interval time.Duration
StartTime time.Time
EndTime time.Time // 零值表示不限 / zero means no end
}
IntervalTrigger 定义定时任务:按固定间隔循环执行。 IntervalTrigger fires repeatedly with a fixed interval.
func (*IntervalTrigger) Build ¶
func (t *IntervalTrigger) Build(p PeriodicTask) (Trigger, error)
Build 解析 Interval 字符串并构造实例;间隔非法时返回错误。 Parses the interval string; returns an error when it is not a positive duration.
func (*IntervalTrigger) Next ¶
func (t *IntervalTrigger) Next(prev time.Time) time.Time
Next 越过 EndTime 返回零值(任务终止),否则按间隔递推。 Returns the zero time once EndTime has passed, otherwise prev+Interval.
func (*IntervalTrigger) Type ¶
func (t *IntervalTrigger) Type() string
Type 返回内置类型名。Returns the built-in type name.
type Options ¶
type Options struct {
Storage StorageMode
DB *gorm.DB // 仅 DB 模式使用 / used in DB mode only
Tick time.Duration // 0 表示默认 1s / 0 means 1s
WheelSize int64 // 0 表示默认 24 / 0 means 24
MaxConcurrency int // 全局并发上限,<=0 不限 / global concurrency limit, <=0 unlimited
ConcurrencyPolicy ConcurrencyPolicy // 并发满时的策略 / policy when the limit is reached
}
Options 为调度器配置,Storage 显式决定任务是否落库: StorageDB 时必须提供 DB;StorageMemory 时忽略 DB,任务一律不落库。 MaxConcurrency 为全局同时执行任务数上限,<=0 表示不限制。 ConcurrencyPolicy 决定达到上限时的行为(等待或跳过)。 Options configures the scheduler; Storage explicitly selects memory or DB mode.
type PeriodicTask ¶
type PeriodicTask struct {
Name string // 任务名称 / job name
Function interface{} // 待调用的函数或方法 / function to invoke
Args Args // 调用参数 / call arguments
StartTime time.Time // 起始时间 / start time
EndTime time.Time // 结束时间,零值表示不限 / end time, zero means unlimited
Cron string // cron 表达式(TriggerType=cron) / cron expression
Interval string // 间隔字符串,如 "5s"(TriggerType=interval) / interval string
LimitedAliveCount int64 // 并发存活上限,<=0 不限 / max concurrent runs, <=0 means unlimited
TriggerType string // 触发器类型名 / trigger type name
TriggerConfig string // 触发器配置串 / trigger configuration string
Trigger Trigger `gorm:"-"` // 可选的触发器实例(优先于 TriggerType)/ optional trigger instance
}
PeriodicTask 描述一个计划任务。 TriggerType 取内置类型(date/interval/cron)或 RegisterTrigger 注册的自定义类型名; TriggerConfig 为自定义类型的配置串,由对应 Trigger.Build 解析。 也可直接注入 Trigger 实例(内存模式免注册),此时类型名自动取其 Type()。 启用数据库模式时,落库的是类型名与配置串,服务重启后可自动恢复。
PeriodicTask describes a scheduled job. TriggerType is either a built-in type (date/interval/cron) or a custom type registered via RegisterTrigger, and TriggerConfig is the configuration string passed to Trigger.Build. A Trigger instance may be injected directly to skip registration.
type SafeMapOfInt ¶
SafeMapOfInt 是并发安全的计数表(键为任务 key,值为当前存活执行数)。 SafeMapOfInt is a concurrency-safe counter map keyed by job key.
func (*SafeMapOfInt) Add ¶
func (sm *SafeMapOfInt) Add(s interface{})
Add 将计数加一,读改写原子完成。 Add increments the counter atomically.
func (*SafeMapOfInt) Delete ¶
func (sm *SafeMapOfInt) Delete(s interface{})
Delete 将计数减一,减到 0 时删除该键。 Delete decrements the counter, removing the key when it reaches zero.
func (*SafeMapOfInt) GetValue ¶
func (sm *SafeMapOfInt) GetValue(s interface{}) int64
GetValue 返回计数,不存在时返回 0。 GetValue returns the counter, or 0 when the key is absent.
func (*SafeMapOfInt) Len ¶
func (sm *SafeMapOfInt) Len() int
Len 返回计数非零的键数量,即当前正在执行的任务数。 Len returns the number of keys with a positive counter, i.e. running jobs.
func (*SafeMapOfInt) Total ¶
func (sm *SafeMapOfInt) Total() int64
Total 返回所有键的计数之和,即当前正在执行的实例总数。 Total returns the sum of all counters, i.e. the number of running executions.
type Scheduler ¶
type Scheduler struct {
Any map[string]interface{} // 函数名 -> 反射方法 / function name to reflect.Value
DB *gorm.DB
RunningCount *SafeMapOfInt
// contains filtered or unexported fields
}
Scheduler 为调度器门面。 存储模式在启动时选定:内存模式任务不落库,DB 模式可在重启后恢复。 Scheduler is the scheduler facade. The storage mode is fixed at startup.
func NewScheduler ¶
NewScheduler 创建调度器,按 DB 是否为 nil 隐式选择存储模式(等价于显式指定 Storage)。 db 为 nil 即内存模式;tick 为时间轮切片精度;wheelSize 为时间轮槽位数。 注意:添加任务前必须先调用 Start。 NewScheduler creates a scheduler, inferring the storage mode from db.
func NewSchedulerWithOptions ¶
NewSchedulerWithOptions 按配置创建调度器,在启动时显式选择内存或落库模式。 Tick/WheelSize 为 0 时使用默认值。 NewSchedulerWithOptions creates a scheduler with an explicit storage mode.
func (*Scheduler) ActiveCount ¶
RunningCount 返回正在执行的任务数(按任务去重)。 注意:与字段 RunningCount 同名冲突,故命名为 ActiveCount。 RunningCount of distinct jobs currently running. Named ActiveCount to avoid clashing with the RunningCount field.
func (*Scheduler) AddTask ¶
func (s *Scheduler) AddTask(key string, p PeriodicTask) error
AddTask 添加任务;触发器校验失败时不会落库。 AddTask adds a job. The job is not persisted when trigger validation fails.
func (*Scheduler) AddTaskFunction ¶
func (s *Scheduler) AddTaskFunction(structs ...interface{})
AddTaskFunction 注册结构体的所有方法,使其可被任务按函数名调用。 参数必须为结构体指针。 AddTaskFunction registers all methods of the given struct pointers so that jobs can invoke them by function name.
func (*Scheduler) ContinueTask ¶
ContinueTask 恢复已暂停的任务。 ContinueTask resumes a paused job.
func (*Scheduler) InitFromDB ¶
func (s *Scheduler) InitFromDB()
InitFromDB 从数据库恢复所有未停止的任务到内存(仅 DB 模式有效)。 InitFromDB restores all non-stopped jobs from the database (DB mode only).
func (*Scheduler) MaxConcurrency ¶
MaxConcurrency 返回当前全局并发上限,<=0 表示不限制。 MaxConcurrency returns the current global concurrency limit; <=0 means unlimited.
func (*Scheduler) PendingCount ¶
PendingCount 返回待执行任务数(已启用、未暂停)。 PendingCount returns the number of enabled, non-paused jobs.
func (*Scheduler) RemoveTask ¶
RemoveTask 删除任务(内存 + 数据库)。 RemoveTask removes a job from memory and the database.
func (*Scheduler) ResetTask ¶
func (s *Scheduler) ResetTask(key string, p PeriodicTask) error
ResetTask 重置任务;任务不存在时等价于新增。 ResetTask updates a job, or adds it when it does not exist yet.
func (*Scheduler) SetMaxConcurrency ¶
SetMaxConcurrency 动态调整全局并发上限,<=0 表示不限制,立即生效。 缩限时已在执行的任务不会被中断,仅阻止新的执行。 SetMaxConcurrency resizes the global concurrency limit at runtime. Shrinking does not interrupt running jobs; it only blocks new ones.
func (*Scheduler) Start ¶
func (s *Scheduler) Start()
Start 启动调度器(幂等):启动时间轮与事件消费循环,并从数据库恢复任务。 注意:必须先 Start 再添加任务。 Start starts the scheduler (idempotent). Add tasks only after Start.
func (*Scheduler) StartTaskNow ¶
StartTaskNow 立即执行一次任务,不改变原调度计划。 StartTaskNow runs a job immediately without changing its schedule.
type Stats ¶
type Stats struct {
Total int // 内存中的任务总数(含已暂停)/ total jobs in memory, including paused
Pending int // 待执行任务数(已启用、未暂停)/ pending jobs, enabled and not paused
Stopped int // 已暂停任务数 / paused jobs
Running int // 正在执行的任务数(按任务去重)/ running jobs, deduplicated by key
Instances int64 // 正在执行的实例总数(含同一任务的多次并发)/ running executions
MaxConcurrency int // 全局并发上限,0 表示不限 / global limit, 0 means unlimited
Skipped int64 // 因并发满被跳过的执行次数 / runs dropped because the limit was reached
}
Stats 返回调度器当前的运行统计。 Stats returns a snapshot of the scheduler runtime counters.
type StorageMode ¶
type StorageMode int
StorageMode 决定计划任务是否落库,启动时选定。 StorageMode decides whether jobs are persisted; chosen at startup.
const ( StorageMemory StorageMode = iota // 内存模式:不落库 / memory mode: no persistence StorageDB // 落库模式:写入 periodic_task 表 / DB mode: persisted )
func (StorageMode) String ¶
func (m StorageMode) String() string
String 返回存储模式名称。Returns the mode name.
type Timer ¶
type Timer struct {
// contains filtered or unexported fields
}
Timer 表示一个待触发的任务,到期后执行其函数。 Timer is a single pending job executed when it expires.
type TimingWheel ¶
type TimingWheel struct {
// contains filtered or unexported fields
}
TimingWheel 是层级时间轮实现(移植自 nsq 的 timing wheel)。 只有当前层能容纳的到期时间留在本层,其余交给上层溢出轮, 因此可以低成本支持跨度远大于 wheelSize*tick 的调度。
TimingWheel is a hierarchical timing wheel (ported from nsq's timing wheel). Expirations beyond the current wheel are delegated to an overflow wheel.
func NewTimingWheel ¶
func NewTimingWheel(tick time.Duration, wheelSize int64) *TimingWheel
NewTimingWheel 创建时间轮,tick 须不小于 1ms,wheelSize 须大于 0。 Creates a timing wheel; tick must be >= 1ms and wheelSize > 0.
type Trigger ¶
type Trigger interface {
Type() string // 类型名 / type name
Next(time.Time) time.Time // 下次执行时间,零值表示终止 / next fire time, zero to stop
Build(PeriodicTask) (Trigger, error) // 由任务配置构造实例 / build an instance from the job
}
Trigger 定义触发器接口。 任务每次执行后调用 Next 计算下次执行时间,返回零值 time.Time{} 表示任务终止; Build 由 PeriodicTask 构造真实例;Type 返回类型名(内置名或 RegisterTrigger 注册名), 用于持久化与重启恢复。
Trigger decides when a job runs. Next returns the zero time.Time to stop. Build constructs a configured instance from a PeriodicTask, and Type returns the type name used for persistence and restart recovery.
func BuildTrigger ¶
func BuildTrigger(p PeriodicTask) (Trigger, error)
BuildTrigger 构造任务的触发器实例: ① PeriodicTask.Trigger 已注入实例时,直接由其 Build 产出(内存模式免注册); ② 否则按 TriggerType 查内置/注册的类型原型,由原型 Build 产出(支持持久化恢复)。
BuildTrigger constructs the trigger of a job: an injected instance wins, otherwise the registered prototype for TriggerType builds it.