job.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. c.AddFunc("30 * * * * *", ReadMsgs)
  14. c.Start()
  15. }
  16. func ReadMsgs() {
  17. var msgs []model.Message
  18. var err error
  19. if msgs, err = svc.QueryMsg(); err != nil {
  20. log.Errorf("%v", err)
  21. return
  22. }
  23. fmt.Println("msg len=", len(msgs))
  24. if len(msgs) == 0 {
  25. return
  26. }
  27. // fmt.Printf("%v\n", msgs)
  28. for _, val := range msgs {
  29. e := SendMsg(&val)
  30. log.Error(e)
  31. }
  32. }
  33. func SendMsg(val *model.Message) (err error) {
  34. // if val.SysName != "tmrWatch_test" {
  35. // return
  36. // } else {
  37. // val.Target = `["oLd1b56PwpexCa0QK4NCkza9TKyY"]`
  38. // }
  39. data := make(map[string]interface{})
  40. targets := make([]string, 10)
  41. if e := json.Unmarshal([]byte(val.MsgContent), &data); e != nil {
  42. log.Errorf("%v", err)
  43. return
  44. }
  45. if e := json.Unmarshal([]byte(val.Target), &targets); e != nil {
  46. log.Errorf("%v", err)
  47. return
  48. }
  49. for _, openid := range targets {
  50. data["touser"] = openid
  51. if jsonstr, e := json.Marshal(data); e != nil {
  52. err = errors.Wrap(e, "SendMessage{json marshal error of data}=%v")
  53. log.Errorf("%v", err)
  54. continue
  55. } else {
  56. if resp, tmperr := notice.MsgTemplate(jsonstr); tmperr != nil {
  57. err = errors.Wrap(tmperr, "SendMessage{send message error}==%v")
  58. log.Errorf("%v", err)
  59. } else {
  60. log.Infof("send msg success%v", string(resp))
  61. if e := svc.UpdateMessage(val); e != nil {
  62. err = errors.Wrap(e, "SendMessage{update message error}=%v")
  63. log.Errorf("%v", err)
  64. }
  65. }
  66. }
  67. }
  68. return
  69. }