timetask.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package timetask
  2. import (
  3. "fmt"
  4. "log"
  5. "strconv"
  6. "strings"
  7. "time"
  8. "app.yhyue.com/moapp/jybase/common"
  9. "bp.jydev.jianyu360.cn/BaseService/userCenter/entity"
  10. )
  11. //已到期企业定时任务
  12. func Run() {
  13. if entity.ConfigJson.IsRun {
  14. go checkEntIsExpire()
  15. log.Println(entity.ConfigJson.CheckEntIsExpire)
  16. }
  17. }
  18. func checkEntIsExpire() {
  19. crontab(false, entity.ConfigJson.CheckEntIsExpire, func() {
  20. defer common.Catch()
  21. log.Println("定时任务更新认证已到期企业开始")
  22. now := time.Now().Format(entity.Date_Full_Layout)
  23. rdata := entity.Mysql.SelectBySql(`select id,name,phone,auth_endTime from entniche_info where auth_endTime < ? and auth_status =1;`, now)
  24. if len(*rdata) > 0 && rdata != nil {
  25. log.Println(fmt.Sprintf("本轮更新已到期企业数量为:%v。", len(*rdata)))
  26. for _, v := range *rdata {
  27. log.Println(fmt.Sprintf("已到期企业id:%v, 企业名称: %s, 企业管理员手机号:%s", v["id"], v["name"], v["phone"]))
  28. }
  29. }
  30. //更新企业
  31. ok := entity.Mysql.UpdateOrDeleteBySql(`UPDATE entniche_info SET auth_status=-2 where auth_endTime < ? and auth_status =1 `, now)
  32. if ok < 0 {
  33. log.Println("更新已到期企业失败")
  34. }
  35. log.Println("定时任务更新认证已到期企业结束")
  36. })
  37. }
  38. //
  39. func crontab(flag bool, c string, f func()) {
  40. array := strings.Split(c, ":")
  41. if len(array) != 2 {
  42. log.Fatalln("定时任务参数错误!", c)
  43. }
  44. if flag {
  45. go f()
  46. }
  47. now := time.Now()
  48. t := time.Date(now.Year(), now.Month(), now.Day(), common.IntAll(array[0]), common.IntAll(array[1]), 0, 0, time.Local)
  49. if t.Before(now) {
  50. t = t.AddDate(0, 0, 1)
  51. }
  52. timer := time.NewTimer(t.Sub(now))
  53. for {
  54. select {
  55. case <-timer.C:
  56. go f()
  57. timer.Reset(24 * time.Hour)
  58. }
  59. }
  60. }
  61. //
  62. func crontabByTicker(flag bool, c string, f func()) {
  63. if c == "0" {
  64. log.Println("定时任务参数有误:", c)
  65. return
  66. }
  67. countdown := 5 * 60
  68. if strings.Contains(c, "h") {
  69. cStr := strings.Split(c, "h")[0]
  70. countdown, _ = strconv.Atoi(cStr)
  71. countdown = countdown * 60 * 60
  72. } else {
  73. countdown, _ = strconv.Atoi(c)
  74. countdown = countdown * 60
  75. }
  76. if flag {
  77. go f()
  78. }
  79. ticker := time.NewTicker(time.Duration(countdown) * time.Second)
  80. go func(t *time.Ticker) {
  81. for {
  82. select {
  83. case <-t.C:
  84. go f()
  85. fmt.Println("get ticker", time.Now().Format("2006-01-02 15:04:05"))
  86. }
  87. }
  88. }(ticker)
  89. }