Golang——time.Ticker定时器

Golang——time.Ticker定时器

ticker一般用来作为时间周期执行命令:

func main() {
	ticker := time.NewTicker(time.Second) // 每隔1s进行一次打印
	for {
		<-ticker.C
		fmt.Println("这是ticker的打印")
	}
}

Ticker结构体

// A Ticker holds a channel that delivers ``ticks'' of a clock
// at intervals.
type Ticker struct {
	C <-chan Time // The channel on which the ticks are delivered.
	r runtimeTimer
}

Ticker保管一个通道,并每隔一段时间向其传递"tick"。

创建时钟周期

time.NewTicker()

func NewTicker(d Duration) *Ticker
NewTicker返回一个新的Ticker,该Ticker包含一个通道字段,并会每隔时间段d就向该通道发送当时的时间。它会调整时间间隔或者丢弃tick信息以适应反应慢的接收者。如果d<=0会panic。关闭该Ticker可以释放相关资源

实例1:在11点35分打印"Golang"

func main() {
	myTicker:=time.NewTicker(time.Second)		//设置时间周期
	for{
		nowTime:=<-myTicker.C		//当前时间
		if nowTime.Hour()==11 && nowTime.Minute()==35{
			fmt.Println("Golang")
			break
		}
	}
}

实例2:每秒打印时间,然后10秒后结束。

package main

import (
	"fmt"
	"time"
)

func main() {
	ticker := time.NewTicker(time.Second)
	defer ticker.Stop()
	done := make(chan bool)
	go func() {
		time.Sleep(10 * time.Second)
		done <- true
	}()
	for {
		select {
		case <-done:
			fmt.Println("Done!")
			return
		case t := <-ticker.C:
			fmt.Println("Current time: ", t)
		}
	}
}

输出结果

Current time:  2022-10-21 09:52:47.7603062 +0800 CST m=+1.029829101
Current time:  2022-10-21 09:52:48.7591099 +0800 CST m=+2.028632801
Current time:  2022-10-21 09:52:49.7620993 +0800 CST m=+3.031622201
Current time:  2022-10-21 09:52:50.7534455 +0800 CST m=+4.022968401
Current time:  2022-10-21 09:52:51.7596767 +0800 CST m=+5.029199601
Current time:  2022-10-21 09:52:52.7634561 +0800 CST m=+6.032979001
Current time:  2022-10-21 09:52:53.7499603 +0800 CST m=+7.019483201
Current time:  2022-10-21 09:52:54.7570725 +0800 CST m=+8.026595401
Current time:  2022-10-21 09:52:55.7489688 +0800 CST m=+9.018491701
Done!

使用Tick()方法

// Tick is a convenience wrapper for NewTicker providing access to the ticking
// channel only. While Tick is useful for clients that have no need to shut down
// the Ticker, be aware that without a way to shut it down the underlying
// Ticker cannot be recovered by the garbage collector; it "leaks".
// Unlike NewTicker, Tick will return nil if d <= 0.
func Tick(d Duration) <-chan Time {
	if d <= 0 {
		return nil
	}
	return NewTicker(d).C
}

实例

// 60秒定期更新一次
	tick := time.Tick(60 * time.Second)
	go func() {
		for {
			<-tick
            err  = do_something(...)
			if err != nil {
                panic(err)
			}
		}
	}()

参考文章

传送门1

传送门2

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

酷酷的Herio

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

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

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

打赏作者

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

抵扣说明:

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

余额充值