golang定时任务详解

栏目: Go · 发布时间: 7年前

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

在程序中经常需要按照指定的周期(以毫秒计)来调用函数或计算表达式,也即实现定时任务,使用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
        }
    }()
}

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


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Beautiful Code

Beautiful Code

Greg Wilson、Andy Oram / O'Reilly Media / 2007-7-6 / GBP 35.99

In this unique work, leading computer scientists discuss how they found unusual, carefully designed solutions to difficult problems. This book lets the reader look over the shoulder of major coding an......一起来看看 《Beautiful Code》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具