sentry.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package data
  2. import (
  3. "time"
  4. "github.com/sirupsen/logrus"
  5. )
  6. var (
  7. stopServerNoticeEnd = "stopServerNoticeEnd"
  8. )
  9. type sentry struct {
  10. Name string
  11. watcher func(msgId, typ, content string) error // hook方法
  12. lastStamp int64
  13. }
  14. func SendToWorld(msgId, typ, content string) error {
  15. /*msgItem := msg.GmPlacard{
  16. MsgId: msgId,
  17. Type: typ,
  18. Content: content,
  19. }
  20. err := gate.SendToWorld(0, &msgItem)
  21. logrus.WithField("type", "SendToWorld").Infoln(msgItem, err)*/
  22. return nil
  23. }
  24. func (worker *sentry) Run() {
  25. for {
  26. time.Sleep(5 * time.Second) // 5秒扫描一次是否有需要通知的公告
  27. now := time.Now().Unix()
  28. worker.lastStamp = now
  29. for _, v := range Db {
  30. if v.EndAt < time.Now().Unix() || v.StartAt > time.Now().Unix() { // 如果最后时间小于当前时间,不执行了
  31. continue
  32. }
  33. // 如果间隔周期内执行过,那么跳过
  34. if v.LastInterval+v.Interval*60 < now {
  35. if worker.watcher != nil {
  36. if err := worker.watcher(v.MsgId, v.Type, v.Content); err != nil {
  37. logrus.WithField("worker", "sentry").Errorln(v, err.Error())
  38. } else {
  39. v.LastInterval = now
  40. v.UpdateAt = now
  41. // 保存到数据库中
  42. Db[v.MsgId] = v
  43. }
  44. if v.LastInterval+v.Interval*60 > v.EndAt { // 如果是最后一次发送消息, 给服务端发送一个特殊的消息
  45. if err := worker.watcher("", stopServerNoticeEnd, ""); err != nil {
  46. logrus.WithField("worker", "sentry").Errorln(v, err.Error())
  47. }
  48. }
  49. }
  50. }
  51. }
  52. }
  53. }