package _1_demo
import (
"fmt"
"github.com/robfig/cron/v3"
"testing"
"time"
)
// 定时任务
func jobTask() {
fmt.Printf( "任务启动: %s \n",time.Now().Format("2006-01-02 15:04:05"))
}
func TestCron(t *testing.T) {
// 创建一个cron对象
c := cron.New()
// 任务调度
enterId, err := c.AddFunc("@every 3s", jobTask)
if err!=nil{
panic(err)
}
fmt.Printf("任务id是 %d \n", enterId)
// 启动定时任务
c.Start()
// 用于阻塞 后面可以使用 select {} 阻塞
time.Sleep(time.Second * 9)
}
type Cron struct {
entries []*Entry // 用于存放job指针对象的数组
chain Chain
stop chan struct{} // 定制调度任务
add chan *Entry // 添加一个调度任务
remove chan EntryID // 移除 一个调度任务
snapshot chan chan []Entry // 正在运行中的调度任务
running bool // 保证整个Cron对象只启动一次 和启动后其他chan正常
logger Logger // 记录日志
runningMu sync.Mutex // 协程锁,确保执行安全
location *time.Location // 时区
parser ScheduleParser // 解析参数
nextID EntryID // 下一个调度任务的id
jobWaiter sync.WaitGroup // 确保单一的调度任务执行完毕
}
// Entry consists of a schedule and the func to execute on that schedule.
type Entry struct {
// ID is the cron-assigned ID of this entry, which may be used to look up a
// snapshot or remove it.
ID EntryID // 任务调度Id,默认是自增 创建任务时返回
// Schedule on which this job should be run.
Schedule Schedule // 调度任务运行
// Next time the job will run, or the zero time if Cron has not been
// started or this entry's schedule is unsatisfiable
Next time.Time // 下次执行时间
// Prev is the last time this job was run, or the zero time if never.
Prev time.Time // 上次执行时间
// WrappedJob is the thing to run when the Schedule is activated.
WrappedJob Job // 执行的任务
// Job is the thing that was submitted to cron.
// It is kept around so that user code that needs to get at the job later,
// e.g. via Entries() can do so.
Job Job
}