xingo 定時(shí)器

2018-01-05 16:51 更新

1) 延遲執(zhí)行

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 ,服務(wù)將會(huì)延遲5秒之后執(zhí)行testTimer


2) 定時(shí)執(zhí)行

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 ,服務(wù)將會(huì)在2016-12-15 18:35:10執(zhí)行testTimer,注意時(shí)間必須是將來(lái)的時(shí)間


3) 循環(huán)執(zhí)行

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 ,服務(wù)將會(huì)每隔5秒執(zhí)行testTimer

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)