mcron

package
v0.5.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 13, 2025 License: MIT Imports: 3 Imported by: 0

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrNilFunc 表示未提供要执行的函数。
	ErrNilFunc = errors.New("m_cron: Func is nil")
	// ErrEmptySpec 表示未提供 cron 表达式。
	ErrEmptySpec = errors.New("m_cron: Spec is empty")
)

Cron在线表达式生成器: https://cron.ciding.cc/

Package m_cron 提供一个简易的定时任务封装,基于 github.com/robfig/cron/v3 默认使用带秒字段的解析器(cron.WithSeconds())。 注意:robfig/cron 不完全兼容 Quartz 的一些扩展语法(如 '?'、L、W、# 等)。 若需兼容 Quartz 风格表达式,建议在调用方做预处理或使用专门支持 Quartz 的库。

示例:

c, err := mcron.New(CronOption{
		Func: func() { fmt.Println("hello") },
		Spec: "0 0 12 * * *", // 带秒的 robfig/cron 表达式
})

if err != nil {
		log.Fatal(err)
}
defer c.Stop()

Functions

This section is empty.

Types

type Cron

type Cron struct {
	// contains filtered or unexported fields
}

Cron 是本包对 github.com/robfig/cron 的封装,便于管理任务与优雅停止。

func New

func New(opt CronOption) (*Cron, error)

New 创建并启动定时任务并返回封装的 *Cron。 当参数不合法或表达式无法解析时返回错误。返回的 Cron 需要在适当时机 Stop()。

Example

ExampleNew 提供 New 函数的使用示例

// 为了避免示例依赖定时器带来的不稳定,直接演示输出
fmt.Println("hello")
Output:

hello

func (*Cron) Remove

func (cr *Cron) Remove()

Remove 删除已注册的任务(若需要按 ID 删除)。

func (*Cron) Stop

func (cr *Cron) Stop()

Stop 优雅停止并等待正在运行的任务完成。

type CronOption

type CronOption struct {
	Func      func() // 定时执行的函数,不能为空
	Spec      string // cron 表达式(带秒时为 6 字段),不能为空
	Immediate bool   // 是否在启动后立即执行一次
}

CronOption 是 New 的配置项。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL