go 实现定时任务 删除 任务等等

go 实现定时任务

Installation

To download the specific tagged release, run:

go get github.com/robfig/cron/[email protected]

Import it in your program as:

import "github.com/robfig/cron/v3"

It requires Go 1.11 or later due to usage of Go Modules.

一种是标准的cron 时间

c := cron.New()

接受5个参数 spec := “*/1 * * * *”

一种是精确到秒的时间

c := cron.New(cron.WithSeconds())

接收6个参数 精确到秒 spec := “*/1 * * * * *”

代码

package main

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

func main() {
	c := cron.New(cron.WithSeconds())
	go try2(c)
	i := 0
	//c := cron.New()
	spec := "*/1 * * * * *"
	id, err := c.AddFunc(spec, func() {
		i++
		fmt.Println("cron running:", i)
		fmt.Println(time.Now())
	})
	fmt.Println("id-->", id)
	fmt.Println("-->", err)
	c.Start()
	go func() {
	time.Sleep(time.Second*10)
	c.Remove(2)
	}()
	select {}
}
func try2(c *cron.Cron) {
	i := 0
	//c := cron.New()
	spec := "*/1 * * * * *"
	id, err := c.AddFunc(spec, func() {
		i++
		fmt.Println("try2:", i)
		fmt.Println(time.Now())
	})
	fmt.Println("try2-->", id)
	fmt.Println("try2-->", err)
	c.Start()

	select {}

}

函数里面 在10秒之后 id 2 的func被终止定时任务 查看输出结果符合要求

输出

id--> 1
--> 
try2--> 2
try2--> 
cron running: 1
try2: 1
2020-02-17 17:15:02.1228203 +0800 CST m=+0.602629601
2020-02-17 17:15:02.1228203 +0800 CST m=+0.602629601
try2: 2
cron running: 2
2020-02-17 17:15:03.0002816 +0800 CST m=+1.480090901
2020-02-17 17:15:03.0002816 +0800 CST m=+1.480090901
try2: 3
2020-02-17 17:15:04.0046654 +0800 CST m=+2.484474701
cron running: 3
2020-02-17 17:15:04.016659 +0800 CST m=+2.496468301
cron running: 4
try2: 4
2020-02-17 17:15:05.0000577 +0800 CST m=+3.479867001
2020-02-17 17:15:05.0000577 +0800 CST m=+3.479867001
cron running: 5
try2: 5
2020-02-17 17:15:06.0024415 +0800 CST m=+4.482250801
2020-02-17 17:15:06.0014435 +0800 CST m=+4.481252801
cron running: 6
try2: 6
2020-02-17 17:15:07.0008291 +0800 CST m=+5.480638401
2020-02-17 17:15:07.0008291 +0800 CST m=+5.480638401
cron running: 7
try2: 7
2020-02-17 17:15:08.0002133 +0800 CST m=+6.480022601
2020-02-17 17:15:08.0002133 +0800 CST m=+6.480022601
try2: 8
cron running: 8
2020-02-17 17:15:09.0016015 +0800 CST m=+7.481410801
2020-02-17 17:15:09.0016015 +0800 CST m=+7.481410801
cron running: 9
try2: 9
2020-02-17 17:15:10.0019844 +0800 CST m=+8.481793701
2020-02-17 17:15:10.0019844 +0800 CST m=+8.481793701
cron running: 10
2020-02-17 17:15:11.0003719 +0800 CST m=+9.480181201
try2: 10
2020-02-17 17:15:11.0013744 +0800 CST m=+9.481183701
cron running: 11
2020-02-17 17:15:12.0017611 +0800 CST m=+10.481570401
cron running: 12
2020-02-17 17:15:13.0001464 +0800 CST m=+11.479955701
cron running: 13
2020-02-17 17:15:14.0015313 +0800 CST m=+12.481340601
cron running: 14
2020-02-17 17:15:15.0009451 +0800 CST m=+13.480754401
cron running: 15
2020-02-17 17:15:16.0003072 +0800 CST m=+14.480116501

意义

意义:用其中的id来中止掉运行的函数 实现了函数的删除和停止运行

go 实现定时任务 删除 任务等等_第1张图片

你可能感兴趣的:(go)