golang定时任务详解

在程序中经常需要按照指定的周期(以毫秒计)来调用函数或计算表达式,也即实现定时任务,使用time包中Tick和Sleep可以轻松实现定时任务
使用Tick每隔100毫秒打印“Hello TigerwolfC”

for range time.Tick(time.Millisecond*100){  		
	fmt.Println("Hello TigerwolfC") 
}

每隔100毫秒打印 “Hello TigerwolfC”,也可以使用 time.Sleep()

for{
	time.Sleep(time.Millisecond* 100)
	fmt.Println("Hello TigerwolfC")
}

每隔5秒执行f()函数

c := time.Tick(5 * time.Second)
for {
	<- c
	go f()
}

也可使用定时器,例如

package main

import (
	"fmt"
	"time"
)

func main() {
	var ch chan int
	//定时任务
	ticker := time.NewTicker(time.Second * 5)
	go func() {
		for range ticker.C {
		fmt.Println(time.Now().Format("2006-01-02 15:04:05"))
		}
		ch <- 1
	}()
	<-ch
}

输出结果:

2018-12-08 08:30:47
2018-12-08 08:30:52
2018-12-08 08:30:57
2018-12-08 08:31:02
2018-12-08 08:31:07
2018-12-08 08:31:12
……

如下例子,使用定时器每隔12小时从MySQL复制用户信息到Redis数据库

func CopyUserInfo() {
   for {
      rows, err := MysqlClient.Query("SELECT name,mail,department,title FROM UsersInfo")
      if err != nil {
         log4go.Info("query mysqlDB fail")
         return
      }

      userInfos := make(map[int]models.UserInfo)
      userInfo := models.UserInfo{}
      i := 0
      for rows.Next() {
         rows.Scan(&userInfo.Name, &userInfo.Mail, &userInfo.Department, &userInfo.Title)
         userInfos[i] = userInfo
         i++
      }

      SetUserNameMail(userInfos)  //save userInfo into Redis
      SetUserDisplaynameMail(userInfos) //save userInfo into Redis
      fmt.Println("userinfo copy to redis successfully")
      ticker := time.NewTicker(time.Hour * 12)
      <-ticker.C
   }

}

启动的时候执行一次,以后每天晚上12点执行

func startTimer(f func()) {
	go func() {
		for {
			f()
			now := time.Now()
			// 计算下一个零点
			next := now.Add(time.Hour * 24)
			next = time.Date(next.Year(), next.Month(), next.Day(), 0,0,0,0,next.Location())
			t := time.NewTimer(next.Sub(now))
			<-t.C
		}
	}()
}

如有不对欢迎指正,相互学习,共同进步。

猜你喜欢

转载自blog.csdn.net/wade3015/article/details/84878511