xingo 定时器

2018-01-05 16:51 更新

1) 延迟执行

func (this *Server) CallLater(durations time.Duration, f func(v ...interface{}), args ...interface{}){
       delayTask := timer.NewTimer(durations, f, args)
       delayTask.Run()
}
示例:

func testTimer(args ...interface {}){
       logger.Info(fmt.Sprintf("%s-%d-%f", args[0], args[1], args[2]))
}
s.CallLater(5*time.Second, testTimer, "viphxin", 10009, 10.999)
//s 为xingo server ,服务将会延迟5秒之后执行testTimer


2) 定时执行

func (this *Server) CallWhen(ts string, f func(v ...interface{}), args ...interface{}){
       loc, err_loc := time.LoadLocation("Local")
       if err_loc != nil{
              logger.Error(err_loc)
              return
       }
       t, err := time.ParseInLocation("2006-01-02 15:04:05", ts, loc)
       now := time.Now()
       //logger.Info(t)
       //logger.Info(now)
       //logger.Info(now.Before(t) == true)
       if err == nil{
              if now.Before(t){
                     this.CallLater(t.Sub(now), f, args...)
              }else{
                     logger.Error("CallWhen time before now")
              }
       }else{
              logger.Error(err)
       }
}

示例:

s.CallWhen("2016-12-15 18:35:10", testTimer, "viphxin", 10009, 10.999)
//s 为xingo server ,服务将会在2016-12-15 18:35:10执行testTimer,注意时间必须是将来的时间


3) 循环执行

func (this *Server)CallLoop(durations time.Duration, f func(v ...interface{}), args ...interface{}){
       go func() {
              delayTask := timer.NewTimer(durations, f, args)
              for {
                     time.Sleep(delayTask.GetDurations())
                     delayTask.GetFunc().Call()
              }
       }()
}
示例:

s.CallLoop(5*time.Second, testTimer, "loop--viphxin", 10009, 10.999)
//s 为xingo server ,服务将会每隔5秒执行testTimer

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号