• 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

  • 相关阅读:
    鸿枫网盘,文件夹面包屑跳转实现功能
    xilinx fpga ultrascale 器件GTX参考时钟注意点
    ModelSim相关实用设置
    redis-cli报错Could not connect to Redis at 127.0.0.1:6379: Connection refused
    SSM - Springboot - MyBatis-Plus 全栈体系(十一)
    有此秘籍,TIF图片转Excel表格不再难
    简单宠物网页设计作业 静态HTML动物介绍网页作业 DW宠物网站模板下载 大学生简单野生动物网页作品代码
    MATLAB关于线性优化和整数线性优化
    5个节约生命的Python小技巧
    Idea:通义千问插件
  • 原文地址:https://blog.csdn.net/yinjl123456/article/details/127115171