robfig/cron/v3 是一个 Golang 的定时任务库

要下载特定的标记版本,请运行:

go get github.com/robfig/cron/v3@v3.0.0

将其导入您的程序中:

import "github.com/robfig/cron/v3"

官方文档 http://godoc.org/github.com/robfig/cron

源码概览

cron 并不是一个很大的库,核心文件与作用如下:

  • chain.go: 装饰器模式,使用 Chain 可以给一个作业添加多个装饰器,以实现日志记录等功能
  • constantdelay.go:顾名思义,提供了一个简单的常量延迟,如 每5分钟,最小粒度支持到秒
  • cron.go:提供核心功能
  • logger.go: 定义了一个 Logger 接口,使之能插入到结构化日志系统中
  • option.go:对默认行为的修改相关
  • parser.go:解析 cron 表达式
  • spec.go:

核心数据结构和接口

type Entry truct
Entry 是对添加到 Cron 中的作业的封装,每个 Entry 有一个 ID,除此之外,Entry 里保存了这个作业上次运行的时间和下次运行的时间。

type EntryID int

type Entry struct {
    ID EntryID
    Schedule Schedule
    Next time.Time
    Prev time.Time
    WrappedJob Job
    Job Job
}
type Cron struct {
    entries   []*Entry          // 保存了所有加入到 Cron 的作业
    chain     Chain
    stop      chan struct{}     // 接收 Stop() 信号的 chan
    add       chan *Entry       // Cron 运行过程中接收 AddJob() 信号的 chan 
    remove    chan EntryID      // 接收移除 Job 信号的 chan
    snapshot  chan chan []Entry // 快照信号
    running   bool              // 标志 Cron 是否在运行中
    logger    Logger
    runningMu sync.Mutex        // Cron 运行前需要抢占该锁,保证并发安全
    location  *time.Location
    parser    ScheduleParser    // cron 表达式的解析器
    nextID    EntryID           // 即将加入的 Job 对应的 Entry 的 ID
    jobWaiter sync.WaitGroup
}

源码解析:
1、 https://blog.csdn.net/zjbyough/article/details/113853582
2、 https://www.cnblogs.com/jiangz222/p/12345566.html?ivk_sa=1024320u

作者:joker.liu  创建时间:2022-09-14 08:41
最后编辑:joker.liu  更新时间:2022-09-14 08:41