package main import ( "github.com/sirupsen/logrus" "math/rand" "sync/atomic" "time" ) const ( MAX_RUN = 3 MIN_RUN = 1 TIME_CHECK = 10 * 60 * time.Second // 十分钟检查一次 //TIME_CHECK = 60 * time.Second // 十分钟检查一次 TIME_RESET_TOTAL_BET = 24 * 3600 * time.Second //TIME_RESET_TOTAL_BET = 300 * time.Second ) var BotQueue *queue var Working int64 var TotalBet int64 var MaxBet int64 func init() { BotQueue = newQueue() } func Run(bots []Account) { AccountShuffle(bots) for _, bot := range bots { BotQueue.rPush(bot) } logrus.Info("bots queue init") ticker := time.NewTicker(TIME_CHECK) defer ticker.Stop() dayTicker := time.NewTicker(TIME_RESET_TOTAL_BET) defer dayTicker.Stop() botCh := make(chan Account) resetBet() master(botCh) for { select { case <-ticker.C: master(botCh) case <-dayTicker.C: resetBet() case exitBot := <-botCh: logrus.Warnf("bot: %s exit!", exitBot.Player) atomic.AddInt64(&Working, -1) BotQueue.rPush(exitBot) // 退出机器人重新加到队尾 } } } func master(botCh chan<- Account) { logrus.Info("check running worker") totalBet := atomic.LoadInt64(&TotalBet) if totalBet >= MaxBet { logrus.Infof("TotalBet:%d >= MaxBet:%d, stop work!", totalBet, MaxBet) return } running := atomic.LoadInt64(&Working) logrus.Infof("running %d bots, queue len: %d", running, BotQueue.getLen()) if running <= MIN_RUN { need := MAX_RUN - running var i int64 for ; i < need; i++ { bot := BotQueue.lPop() if bot == nil { logrus.Error("bot queue empty!!!") break } go worker(bot.(Account), botCh) } } } func worker(bot Account, botCh chan<- Account) { logrus.Infof("bot: %s running~", bot.Player) atomic.AddInt64(&Working, 1) for { bet, err := Transfer(bot.Player, bot.StarId) if err != nil { // 下注失败退出 logrus.WithField("error", err).Warnf("bot: %s transfer error", bot.Player) break } if atomic.AddInt64(&TotalBet, bet) >= atomic.LoadInt64(&MaxBet) { logrus.Infof("TotalBet >= MaxBet, bot: %s stop", bot.Player) break } rand.Seed(time.Now().UnixNano()) c := rand.Intn(6) + 15 time.Sleep(time.Duration(c) * time.Second) } botCh <- bot } func resetBet() { rand.Seed(time.Now().UnixNano()) max := rand.Int63n(15000001) + 35000000 // [3500, 5000] EOS //max := rand.Int63n(5000) + 10000 // [3500, 5000] EOS atomic.StoreInt64(&MaxBet, max) atomic.StoreInt64(&TotalBet, 0) logrus.Infof("Reset MaxBet:%d, TotalBet:%d", max, 0) }