timetask.go 2.3 KB

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