使用 Go 語言實現定時任務:輕鬆掌握 Cron 表達式
一、cron 基本使用
1、使用舉例
package main
import (
"fmt"
"github.com/robfig/cron"
)
//主函數
func main() {
cron2 := cron.New() //創建一個cron實例
//執行定時任務(每5秒執行一次)
err:= cron2.AddFunc("*/5 * * * * *", print5)
if err!=nil{
fmt.Println(err)
}
//啓動/關閉
cron2.Start()
defer cron2.Stop()
select {
//查詢語句,保持程序運行,在這裏等同於for{}
}
}
//執行函數
func print5() {
fmt.Println("每5s執行一次cron")
}
2、配置
┌─────────────second 範圍 (0 - 60)
│ ┌───────────── min (0 - 59)
│ │ ┌────────────── hour (0 - 23)
│ │ │ ┌─────────────── day of month (1 - 31)
│ │ │ │ ┌──────────────── month (1 - 12)
│ │ │ │ │ ┌───────────────── day of week (0 - 6)
│ │ │ │ │ │
│ │ │ │ │ │
* * * * * *
3、多個 crontab 任務
package main
import (
"fmt"
"github.com/robfig/cron"
)
type TestJob struct {
}
func (this TestJob) Run() {
fmt.Println("testJob1...")
}
type Test2Job struct {
}
func (this Test2Job) Run() {
fmt.Println("testJob2...")
}
//啓動多個任務
func main() {
c := cron.New()
spec := "*/5 * * * * ?"
//AddJob方法
c.AddJob(spec, TestJob{})
c.AddJob(spec, Test2Job{})
//啓動計劃任務
c.Start()
//關閉着計劃任務, 但是不能關閉已經在執行中的任務.
defer c.Stop()
select {}
}
/*
testJob1...
testJob2...
testJob1...
testJob2...
*/
二、gin 框架 cron 應用
- 目錄結構
.
├── main.go
└── pkg
└── jobs
├── job_cron.go // 分佈式任務配置
└── test_task.go // 具體任務實例
1、main.go
package main
import (
"go_cron_demo/pkg/jobs"
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
jobs.InitJobs()
r := gin.Default()
r.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "hello World!")
})
r.Run(":8000")
}
2、pkg/jobs/job_cron.go
package jobs
import (
"github.com/robfig/cron"
)
var mainCron *cron.Cron
func init() {
mainCron = cron.New()
mainCron.Start()
}
func InitJobs() {
// 每5s鐘調度一次,並傳參
mainCron.AddJob(
"*/5 * * * * ?",
TestJob{Id: 1, Name: "zhangsan"},
)
}
/* 運行結果
1 zhangsan
testJob1...
1 zhangsan
testJob1...
*/
3、pkg/jobs/test_task.go
package jobs
import "fmt"
type TestJob struct {
Id int
Name string
}
func (this TestJob) Run() {
fmt.Println(this.Id, this.Name)
fmt.Println("testJob1...")
}
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/MSagqznZuyFVE-dEi3SA-w