Go整合cron实现定时任务

简介: Go整合cron实现定时任务

下载安装:

go get github.com/robfig/cron

v3版本安装(适用于Go 1.11版本及之后的):

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

代码:

package main

import (
    "fmt"
    "github.com/robfig/cron/v3"
    "time"
)

func main() {
    methodB()
}

func methodA() {
    c := cron.New(cron.WithSeconds()) //精确到秒级,V3版本之后提供的
    //定时任务
    spec := "*/1 * * * * ?" //cron表达式,每秒一次
    c.AddFunc(spec, func() {
        fmt.Println("methodA 每秒一次...")
    })
    c.Start()
    select {} //阻塞主线程停止
}

func methodB() {
    c := cron.New()
    //定时任务
    spec := "*/1 * * * * ?" //cron表达式,每秒一次
    c.AddFunc(spec, func() {
        fmt.Println("methodA 每秒一次...")
        time.Sleep(time.Second*5)
        c.Stop()//停止任务
    })
    c.Start()
    select {
    }
}

func methodC() {
    fmt.Println("methodC 定时任务C")
}

func methodE() {
    fmt.Println("methodC 定时任务C")
}

func methodD() {
    c := cron.New()
    //定时任务
    spec := "*/1 * * * * ?" //cron表达式,每秒一次
    c.AddFunc(spec, methodE)
    c.AddFunc(spec, methodC)
    c.Start()
    select {} //阻塞主线程停止
}

常用的cron字符串:

https://blog.csdn.net/ysq222/article/details/88965936

相关文章
|
4月前
|
Go
Go 定时任务方法封装
Go 定时任务方法封装
26 0
|
5月前
|
Linux Go API
GO的定时器Timer 和定时任务cron
GO的定时器Timer 和定时任务cron
|
6月前
|
Serverless Go
函数计算FC中,你可以使用Go语言的`timer`包来创建定时任务
函数计算FC中,你可以使用Go语言的`timer`包来创建定时任务
51 1
|
8月前
|
Go
Go 定时任务方法封装
Go 定时任务方法封装
63 0
|
9月前
|
Linux Shell Go
GO的定时器Timer 和定时任务cron
GO的定时器Timer 和定时任务cron
GO的定时器Timer 和定时任务cron
|
存储 缓存 NoSQL
一文搞懂Go整合captcha实现验证码功能
一文搞懂Go整合captcha实现验证码功能
Go整合Logrus实现日志打印
Go整合Logrus实现日志打印
|
SQL Prometheus Cloud Native
Go整合gorm实现CRUD
Go整合gorm实现CRUD
|
XML JSON Java
RPC框架之Thrift—实现Go和Java远程过程调用
RPC框架之Thrift—实现Go和Java远程过程调用

热门文章

最新文章