Golang cron 定时器和定时任务

Golang cron 定时器和定时任务

Golang中time包有两个定时器,分别为 ticker 和 timer。两者都可以实现定时功能,但各自都有自己的使用场景。

timer和ticker的区别

  • ticker定时器表示每隔一段时间就执行一次,一般可执行多次。

  • timer定时器表示在一段时间后执行,默认情况下只执行一次,如果想再次执行的话,每次都需要调用 time.Reset() 方法,此时效果类似ticker定时器。同时也可以调用 Stop() 方法取消定时器

  • timer定时器比ticker定时器多一个 Reset() 方法,两者都有 Stop() 方法,表示停止定时器,底层都调用了stopTimer() 函数。

Timer

Timer是一个定时器。代表未来的一个单一事件,你可以告诉timer你要等待多长时间。

package main

import (
    "fmt"
    "time"
)

func main() {

    //设置定时器为3秒
    timer := time.NewTimer(3 * time.Second)
    fmt.Println("当前时间为:", time.Now())

    t := <-timer.C //从定时器拿数据
    fmt.Println("当前时间为:", t)
}

Ticker

Ticker是一个周期触发定时的计时器,它会按照一个时间间隔往channel发送系统当前时间,而channel的接收者可以以固定的时间间隔从channel中读取事件。

Ticker是一个定时触发的计时器,
它会以一个间隔(interval)往channel发送一个事件(当前时间),
而channel的接收者可以以固定的时间间隔从channel中读取事件。

package main

import (
    "fmt"
    "time"
)

func main() {

    //创建一个周期性的定时器
    ticker := time.NewTicker(3 * time.Second)
    fmt.Println("当前时间为:", time.Now())

    go func() {
        for {

            //从定时器中获取数据
            t := <-ticker.C
            fmt.Println("当前时间为:", t)

        }
    }()

    for {
        time.Sleep(time.Second * 1)
    }
}

cron 定时任务

package main

import (
	"github.com/robfig/cron"
	"log"
	"time"
)

func main() {
	//cron1()

	//cron2()

	cron3()

	select {
	}
}

func cron1()  {
	log.Println("Starting...")
	c := cron.New()
	c.AddFunc("* * * * * *", func() {
		log.Println("Run models.CleanAllTag...")
	})
	c.AddFunc("* * * * * *", func() {
		log.Println("Run models.CleanAllArticle...")
	})

	c.Start()

	t1 := time.NewTimer(time.Second * 10)
	for {
	select {
	case <-t1.C:
	    t1.Reset(time.Second * 10)
	}
	}
}

func cron2()  {
	log.Println("Starting...")
	c := cron.New()  // 新建一个定时任务对象
	c.AddFunc("* * * * * *", func() {
		log.Println("hello world")
	})  // 给对象增加定时任务
	c.Start()
	//select {
	//}
	time.Sleep(10 * time.Second)
	c.Stop()
}

func cron3()  {
	log.Println("Starting...")

	c := cron.New()
	h := Hello{"I Love You!"}
	// 添加定时任务
	c.AddJob("*/2 * * * * *", h)
	// 添加定时任务 5秒执行一次
	c.AddFunc("*/5 * * * * *", func() {
		log.Println("hello word")
	})

	s, err := cron.Parse("*/3 * * * * *")
	if err != nil {
		log.Println("Parse error")
	}
	h2 := Hello{"I Hate You!"}
	c.Schedule(s, h2)
	// 其中任务
	c.Start()
	// 关闭任务
	defer c.Stop()
}

type Hello struct {
	Str string
}

func(h Hello) Run() {
	log.Println(h.Str)
}

参考链接:
https://blog.haohtml.com/archives/19859
https://studygolang.com/articles/17624
https://www.jianshu.com/p/fd3dda663953
https://blog.51cto.com/u_13914991/2294357
https://www.cnblogs.com/yinzhengjie/p/12244385.html
http://t.zoukankan.com/yinzhengjie-p-12245289.html
https://blog.51cto.com/u_13914991/2294357

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

beyond阿亮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值