runner.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package main
  2. import (
  3. "github.com/sirupsen/logrus"
  4. "math/rand"
  5. "sync/atomic"
  6. "time"
  7. )
  8. const (
  9. MAX_RUN = 3
  10. MIN_RUN = 1
  11. TIME_CHECK = 10 * 60 * time.Second // 十分钟检查一次
  12. )
  13. var BotQueue *queue
  14. var Working int64
  15. func init() {
  16. BotQueue = newQueue()
  17. }
  18. func Run(bots []Account) {
  19. AccountShuffle(bots)
  20. for _, bot := range bots {
  21. BotQueue.rPush(bot)
  22. }
  23. logrus.Info("bots queue init")
  24. ticker := time.NewTicker(TIME_CHECK)
  25. defer ticker.Stop()
  26. botCh := make(chan Account)
  27. master(botCh)
  28. for {
  29. select {
  30. case <-ticker.C:
  31. master(botCh)
  32. case exitBot := <-botCh:
  33. logrus.Warnf("bot: %s exit!", exitBot.Player)
  34. atomic.AddInt64(&Working, -1)
  35. BotQueue.rPush(exitBot) // 退出机器人重新加到队尾
  36. }
  37. }
  38. }
  39. func master(botCh chan<- Account) {
  40. logrus.Info("check running worker")
  41. running := atomic.LoadInt64(&Working)
  42. logrus.Infof("running %d bots, queue len: %d", running, BotQueue.getLen())
  43. if running <= MIN_RUN {
  44. need := MAX_RUN - running
  45. var i int64
  46. for ; i < need; i++ {
  47. bot := BotQueue.lPop()
  48. if bot == nil {
  49. logrus.Error("bot queue empty!!!")
  50. break
  51. }
  52. go worker(bot.(Account), botCh)
  53. }
  54. }
  55. }
  56. func worker(bot Account, botCh chan<- Account) {
  57. logrus.Infof("bot: %s running~", bot.Player)
  58. atomic.AddInt64(&Working, 1)
  59. for {
  60. rand.Seed(time.Now().UnixNano())
  61. c := rand.Intn(51) + 30
  62. err := Transfer(bot.Player, bot.StarId)
  63. if err != nil { // 下注失败退出
  64. logrus.WithField("error", err).Warnf("bot: %s transfer error", bot.Player)
  65. break
  66. }
  67. time.Sleep(time.Duration(c) * time.Second)
  68. }
  69. botCh <- bot
  70. }