job.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package service
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/pkg/errors"
  6. "github.com/robfig/cron"
  7. "kpt.notice/apiserver/model"
  8. "kpt.notice/middleware/notice"
  9. "kpt.notice/pkg/log"
  10. )
  11. func JobInit() {
  12. c := cron.New()
  13. // ReadMsgs()
  14. // notice.SendMessage(nil)
  15. c.AddFunc("30 * * * * *", ReadMsgs)
  16. c.Start()
  17. }
  18. func ReadMsgs() {
  19. var msgs []model.Message
  20. var err error
  21. if msgs, err = svc.QueryMsg(); err != nil {
  22. log.Errorf("%v", err)
  23. return
  24. }
  25. fmt.Println("msg len=", len(msgs))
  26. if len(msgs) == 0 {
  27. return
  28. }
  29. // fmt.Printf("%v\n", msgs)
  30. for _, val := range msgs {
  31. e := SendMsg(&val)
  32. log.Error(e)
  33. }
  34. }
  35. func SendMsg(val *model.Message) (err error) {
  36. svc.UpdateMessageStatus(val.ID)
  37. // if val.SysName != "tmrWatch_test" {
  38. // return
  39. // } else {
  40. // val.Target = `["oLd1b56PwpexCa0QK4NCkza9TKyY"]`
  41. // }
  42. data := make(map[string]interface{})
  43. targets := make([]string, 10)
  44. if e := json.Unmarshal([]byte(val.MsgContent), &data); e != nil {
  45. log.Errorf("%v", err)
  46. return
  47. }
  48. if e := json.Unmarshal([]byte(val.Target), &targets); e != nil {
  49. log.Errorf("%v", err)
  50. return
  51. }
  52. for _, openid := range targets {
  53. data["touser"] = openid
  54. if jsonstr, e := json.Marshal(data); e != nil {
  55. err = errors.Wrap(e, "SendMessage{json marshal error of data}=%v")
  56. log.Errorf("%v", err)
  57. continue
  58. } else {
  59. if resp, tmperr := notice.MsgTemplate(jsonstr); tmperr != nil {
  60. err = errors.Wrap(tmperr, "SendMessage{send message error}==%v")
  61. log.Errorf("%v", err)
  62. } else {
  63. log.Infof("send msg success%v", string(resp))
  64. if e := svc.UpdateMessage(val); e != nil {
  65. err = errors.Wrap(e, "SendMessage{update message error}=%v")
  66. log.Errorf("%v", err)
  67. }
  68. }
  69. }
  70. }
  71. return
  72. }