首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >Go整合cron实现定时任务

Go整合cron实现定时任务

原创
作者头像
闫同学
发布2023-10-14 17:22:47
发布2023-10-14 17:22:47
3310
举报
文章被收录于专栏:扯编程的淡扯编程的淡

下载安装:

代码语言:shell
复制
go get github.com/robfig/cron

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

代码语言:shell
复制
go get github.com/robfig/cron/v3@v3.0.0

代码:

代码语言:go
复制
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

我正在参与2023腾讯技术创作特训营第二期有奖征文,瓜分万元奖池和键盘手表

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档