cron 中开启协程执行任务
package cron
import (
"project/internal/jobs"
"github.com/robfig/cron/v3"
)
func Run() {
c := cron.New(cron.WithSeconds())
// 每分钟的第 40 秒执行
c.AddJob("40, * * * * *", jobs.OneMinuteJob{})
// 启动一个 goroutine 去执行的
c.Start()
// 阻止主线程停止
select {}
}
package jobs
import (
"fmt"
"sync"
"time"
)
var fullTimeFormat = "2006-01-02 15:04:05"
type OneMinuteJob struct {
}
var wg sync.WaitGroup
func (om OneMinuteJob) Run() {
// 缓冲通道
ch := make(chan int, 3)
for i := 0; i < 10; i++ {
ch <- i
wg.Add(1)
go test(ch)
}
close(ch)
wg.Wait()
}
func test(ch chan int) {
defer wg.Done()
time.Sleep(time.Second * 3)
i := <-ch
fmt.Println("i =", i, time.Now().Format(fullTimeFormat))
}
zhpj@localhost project % go run main.go cron
i = 0 2024-03-27 20:31:43
i = 1 2024-03-27 20:31:43
i = 2 2024-03-27 20:31:43
i = 3 2024-03-27 20:31:46
i = 4 2024-03-27 20:31:46
i = 5 2024-03-27 20:31:46
i = 6 2024-03-27 20:31:49
i = 7 2024-03-27 20:31:49
i = 8 2024-03-27 20:31:49
i = 9 2024-03-27 20:31:52
i = 0 2024-03-27 20:32:43
i = 1 2024-03-27 20:32:43
i = 2 2024-03-27 20:32:43
i = 3 2024-03-27 20:32:46
i = 4 2024-03-27 20:32:46
i = 5 2024-03-27 20:32:46
i = 6 2024-03-27 20:32:49
i = 7 2024-03-27 20:32:49
i = 8 2024-03-27 20:32:49
i = 9 2024-03-27 20:32:52
参考文章:
Go 并发编程(一):协程 goroutine、channel、协程池
标签:03,27,协程,32,31,开启,cron,20,2024 From: https://www.cnblogs.com/zhpj/p/18100305/open-the-coroutine-execution-task-in-cron-2ilqmf