知识小结-04go语言定时器

1、go channel
channel是Golang在语言层面提供的goroutine间的通信方式,比Unix管道更易用也更轻便。

channel主要用于进程内各goroutine间通信,如果需要跨进程通信,建议使用分布式系统的方法来解决。

注:channel可以看作是一个公共队列,也可以当成公共队列使用

例如:

var MainChannel = make(chan FuncCallInfo)
FuncCallInfo为队列类型,MainChannel为队列名

注:在go语言中make用于申请空间相当于malloc

MainChannel <- funcCaller
将变量funcCaller写入队列

for funcs := range plainObject.MainChannel {}
循环读取队列中的值

<- funcCaller
读取队首的值

2、定时器的源码

type Timer struct {
  C <-chan Time
  r runtimeTimer
}

3、定时代码解析

func Timer() {
   tick1 := time.NewTicker(1 * time.Minute)
   tick2 := time.NewTicker(30 * time.Minute)
   for {
      select {
      case <-tick1.C:
         fmt.Println("获取重启结果.........")
         status := "ok"
 if status == "running" {
            fmt.Println("重启成功,通知")
            return
 }
         if status == "error" {
            fmt.Println("重启失败,通知")
            return
 }
         fmt.Println("未获取到继续获取")
         break
 case <-tick2.C:
         fmt.Println("获取重启结果超时,发送邮件通知管理员")
         return
 }
   }
}

//time.NewTicker()函数是每隔一段时间向队列Timer .C中写入数据,死循环读取公共队列的值

发布了11 篇原创文章 · 获赞 0 · 访问量 86

猜你喜欢

转载自blog.csdn.net/weixin_42282999/article/details/104459101