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字符串:

blog.csdn.net/ysq222/arti…



相关文章
|
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远程过程调用
|
监控 测试技术 Go
用 Go 从零实现日志包 - 第零篇 序言
设计一个日志包,需要考虑的基础功能有日志级别设置、标准输出和文件、输出格式配置、日志的时间戳、文件与打印行号、正文。高级功能有按级别分类输出、支持结构化日志、支持日志轮转。
110 0