Ejemplo n.º 1
0
 /// <summary>
 ///
 /// </summary>
 void HandleTimerCmd()
 {
     if (!_timerService.Enabled)
     {
         _timerService.Start();
         StartBtnText = "Stop Timer";
         elapsedTime  = 0;
     }
     else
     {
         _timerService.Stop();
         StartBtnText = "Start Timer";
         AddEntry();
     }
     IsRunning = _timerService.Enabled;
 }
Ejemplo n.º 2
0
        public void TimerService_TimerStopped_NoEventThrown()
        {
            // Arrange
            var timerElapsedEvent = new AutoResetEvent(false);
            var unitUnderTest     = new TimerService();

            unitUnderTest.Elapsed += (sender, args) => timerElapsedEvent.Set();
            unitUnderTest.Start(100);

            // Act
            unitUnderTest.Stop();
            timerElapsedEvent.Reset();

            // Assert
            Assert.IsFalse(timerElapsedEvent.WaitOne(200), "Did not expected Elapsed event");
        }
Ejemplo n.º 3
0
        public void TimerService_ShouldShouldReturnSameTimeSinceStart_FromBothMethods()
        {
            var timerService = new TimerService();
            var settingsMock = new Mock <ISimulationSettings>();

            settingsMock.Setup(s => s.IncomingFlights).Returns(new Mock <List <Flight> >().Object);
            settingsMock.Setup(s => s.OutgoingFlights).Returns(new Mock <List <Flight> >().Object);
            settingsMock.Setup(s => s.Multiplier).Returns(1);

            timerService.SetSettings(settingsMock.Object);

            timerService.Start();
            Thread.Sleep(2000);
            timerService.Stop();

            timerService.GetTicksSinceSimulationStart().ShouldBeInRange(timerService.GetTimeSinceSimulationStart().Ticks - 5, timerService.GetTimeSinceSimulationStart().Ticks + 5);
        }
Ejemplo n.º 4
0
        public void TimerService_TimerResumed_EventsThrown()
        {
            // Arrange
            var timerElapsedEvent = new AutoResetEvent(false);
            var unitUnderTest     = new TimerService();

            unitUnderTest.Elapsed += (sender, args) => timerElapsedEvent.Set();
            unitUnderTest.Start(100);

            // Act
            unitUnderTest.Pause();
            timerElapsedEvent.Reset();
            unitUnderTest.Resume();

            // Assert
            Assert.IsTrue(timerElapsedEvent.WaitOne(200), "Expected Elapsed event");
            Assert.IsTrue(timerElapsedEvent.WaitOne(200), "Expected 2nd Elapsed event");
        }
Ejemplo n.º 5
0
        public void TimerService_TimerStarted_IntervalCorrect()
        {
            // Arrange
            const int eventsToCapture   = 10;
            const int eventInterval     = 300;
            var       timerElapsedEvent = new AutoResetEvent(false);
            var       unitUnderTest     = new TimerService();
            var       eventList         = new long[eventsToCapture];
            var       eventCount        = 0;

            unitUnderTest.Elapsed += (sender, args) =>
            {
                if (eventCount < eventsToCapture)
                {
                    eventList[eventCount] = DateTime.Now.Ticks;
                }
                eventCount++;
                if (eventCount == eventsToCapture)
                {
                    timerElapsedEvent.Set();
                }
            };

            // Act
            unitUnderTest.Start(eventInterval);

            timerElapsedEvent.WaitOne(5000);

            // Assert
            for (var i = 0; i < eventsToCapture - 1; i++)
            {
                var timeSpan = new TimeSpan(eventList[i + 1] - eventList[i]);
                Console.WriteLine(timeSpan.TotalMilliseconds);

                Assert.IsTrue(Math.Abs(eventInterval - timeSpan.TotalMilliseconds) < 20,
                              $"Interval not correct between {i} and {i + 1}, difference = {timeSpan.TotalMilliseconds}");
            }

            //Assert.AreEqual();
        }
Ejemplo n.º 6
0
        public TimerClient()
        {
            // Registers the HTTP Channel so that this client can receive
            // events from the remote service.

            BinaryServerFormatterSinkProvider serverProv = new BinaryServerFormatterSinkProvider();

            serverProv.TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full;
            BinaryClientFormatterSinkProvider clientProv = new BinaryClientFormatterSinkProvider();

            IDictionary props = new Hashtable();

            props["port"] = 0;
            HttpChannel channel = new HttpChannel(props, clientProv, serverProv);

            ChannelServices.RegisterChannel(channel);

            WellKnownClientTypeEntry remoteType = new WellKnownClientTypeEntry(typeof(TimerService), "http://localhost:9000/MyService/TimerService.soap");

            RemotingConfiguration.RegisterWellKnownClientType(remoteType);

            TimerService groupTimer = new TimerService();

            groupTimer.MinutesToTime = 4.0;

            // Registers this client as a lease sponsor so that it can
            // prevent the expiration of the TimerService.
            ILease leaseObject = (ILease)RemotingServices.GetLifetimeService(groupTimer);

            leaseObject.Register(this);

            // Subscribes to the event so that the client can receive notifications from the server.
            groupTimer.TimerExpired += new TimerExpiredEventHandler(OnTimerExpired);
            Console.WriteLine("Connected to TimerExpired event");

            groupTimer.Start();
            Console.WriteLine("Timer started for {0} minutes.", groupTimer.MinutesToTime);
            Console.WriteLine("Press enter to end the client process.");
            Console.ReadLine();
        }
Ejemplo n.º 7
0
        public void TimerService_CheckForIncomingFlights_GetsTriggered()
        {
            var timerService = new TimerService();
            var settingsMock = new Mock <ISimulationSettings>();

            settingsMock.Setup(s => s.IncomingFlights).Returns(new List <Flight>()
            {
                new Flight()
                {
                    TimeToFlightSinceSimulationStart = timerService.ConvertMillisecondsToTimeSpan(1000),
                    FlightState = FlightState.Incoming
                }
            });
            settingsMock.Setup(s => s.OutgoingFlights).Returns(new List <Flight>());
            settingsMock.Setup(s => s.Multiplier).Returns(1);

            timerService.SetSettings(settingsMock.Object);

            timerService.Start();
            Thread.Sleep(2000);

            settingsMock.Object.IncomingFlights.First().FlightState.ShouldBe(FlightState.Landed);
        }
Ejemplo n.º 8
0
        public void TimerTest_Normal()
        {
            var timer = new TimerService {
                Interval = TimeSpan.FromMilliseconds(100)
            };
            var beforeTime    = DateTime.Now;
            var notifications = new List <TimeSpan>();

            timer.Elapsed += (sender, e) =>
            {
                // 開始前時間からの経過時間を保持しておく
                notifications.Add(DateTime.Now - beforeTime);
            };
            timer.Start();
            // タイマーを動作させるため、スレッドをスリープさせる
            System.Threading.Thread.Sleep(TimeSpan.FromMilliseconds(1000));
            timer.Stop();

            // スレッドスイッチのオーバーヘッドがあるため、スリープ時間をIntervalで割った数分きっかり
            // 通知が来たりしない。
            // インターバル100[ms]で、待機時間が1000[ms]の為、5回以上通知が来ていれば良いものとする
            int count = notifications.Count;

            Assert.IsTrue(5 < notifications.Count);

            // Intervalの±20%の間に収まっていれば良いものとする
            for (int i = 0; i < notifications.Count - 1; i++)
            {
                Assert.IsTrue(TimeSpan.FromMilliseconds(100 * 0.8) < (notifications[i + 1] - notifications[i]));
                Assert.IsTrue((notifications[i + 1] - notifications[i]) < TimeSpan.FromMilliseconds(100 * 1.2));
            }

            // 本当に停止しているか確認する
            System.Threading.Thread.Sleep(TimeSpan.FromMilliseconds(500));
            Assert.AreEqual(count, notifications.Count);
        }
Ejemplo n.º 9
0
        public static void Main(string[] args)
        {
            //挂载全局异常处理
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            if (GCSettings.IsServerGC)
            {
                Console.WriteLine("GC优化已开启");
            }

            var config = Configure.Inst;

            if (!config.Load())
            {
                return;
            }

            int workerCount = config.workerCount + noTableWorkerCount;

            dbSvc.Start(config.dbConnectStr, workerCount);
            dbHelper.Start();
            workerMgr.Start(workerCount);
            if (!server.Start(config.serverPort, 10000))
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("端口:{0}被占用,请按任意键退出", config.serverPort);
                Console.ResetColor();
                Console.ReadKey();
                return;
            }
            moduleManager.Start();
            timerSvc.Start();

            Console.WriteLine("游戏服务器启动完毕,端口:{0}", config.serverPort);

            //Thread thread = new Thread(ClearMemoryThreadProc);
            //thread.IsBackground = true;
            //thread.Start();

            while (true)
            {
                var key = Console.ReadKey();

                if (key.Key == ConsoleKey.S)
                {
                    Console.WriteLine("");
                    Console.WriteLine("当前连接数:{0} 连接池存量:{1}",
                                      server.connectNum, server.GetSessionPoolCount());
                    Console.WriteLine("支持游戏:{0}", Configure.Inst.supportGames);
                }
                if (key.Key == ConsoleKey.T)
                {
                    Configure.Inst.isShowStat = !Configure.Inst.isShowStat;

                    Console.WriteLine("");
                    if (Configure.Inst.isShowStat)
                    {
                        Console.WriteLine("已打开统计信息显示");
                    }
                    else
                    {
                        Console.WriteLine("已关闭统计信息显示");
                    }
                }
                if (key.Key == ConsoleKey.C)
                {
                    Console.Clear();
                }
                if (key.Key == ConsoleKey.Q)
                {
                    break;
                }
                if (key.Key == ConsoleKey.R)
                {
                    Console.WriteLine("");
                    moduleManager.gameModule.LoadAllConfigs();
                }
                if (key.Key == ConsoleKey.D1)
                {
                    Console.WriteLine("");
                    moduleManager.gameModule.SetAllGameIsShowInfo(true);
                    Console.WriteLine("已打开游戏内信息显示");
                }
                if (key.Key == ConsoleKey.D2)
                {
                    Console.WriteLine("");
                    moduleManager.gameModule.SetAllGameIsShowInfo(false);
                    Console.WriteLine("已关闭游戏内信息显示");
                }
                //if(key.Key == ConsoleKey.W)
                //{
                //    dbHelper.LogPlayGame(@"D:\Work\ChessServers\bin\GameServer\Games\Br1", "test", "12312414", "阿拉丁", 0, 100, new JObject());
                //    dbHelper.LogGame(@"D:\Work\ChessServers\bin\GameServer\Games\Br1", "test", "阿拉丁", 0, 100, new JObject());
                //}

                Thread.Sleep(100);
            }

            timerSvc.Stop();
            moduleManager.Stop();
            server.Stop();
            workerMgr.Stop();
            dbHelper.Stop();
            dbSvc.Stop();
        }
Ejemplo n.º 10
0
        public static void Main(string[] args)
        {
            //挂载全局异常处理
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            if (GCSettings.IsServerGC)
            {
                Console.WriteLine("GC优化已开启");
            }

            var config = Configure.Inst;

            if (!config.Load())
            {
                return;
            }

            dbSvc.Start(config.dbConnectStr, config.workerCount + 1);
            dbHelper.Start();
            workerMgr.Start(config.workerCount);
            if (!server.Start(config.serverPort, 10000))
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("端口:{0}被占用,请按任意键退出", config.serverPort);
                Console.ResetColor();
                Console.ReadKey();
                return;
            }
            moduleManager.Start();
            timerSvc.Start();

            Console.WriteLine("大厅服务器启动完毕,端口:{0}", config.serverPort);

            while (true)
            {
                var key = Console.ReadKey();

                if (key.Key == ConsoleKey.S)
                {
                    Console.WriteLine("");
                    Console.WriteLine("当前连接数:{0} 连接池存量:{1}",
                                      server.connectNum, server.GetSessionPoolCount());
                }
                if (key.Key == ConsoleKey.T)
                {
                    Configure.Inst.isShowStat = !Configure.Inst.isShowStat;

                    Console.WriteLine("");
                    if (Configure.Inst.isShowStat)
                    {
                        Console.WriteLine("已打开统计信息显示");
                    }
                    else
                    {
                        Console.WriteLine("已关闭统计信息显示");
                    }
                }
                if (key.Key == ConsoleKey.C)
                {
                    Console.Clear();
                }
                if (key.Key == ConsoleKey.Q)
                {
                    break;
                }

                Thread.Sleep(100);
            }

            timerSvc.Stop();
            moduleManager.Stop();
            server.Stop();
            workerMgr.Stop();
            dbHelper.Stop();
            dbSvc.Stop();
        }
Ejemplo n.º 11
0
        public void TimerTest_UninitializedInterval()
        {
            var timer = new TimerService();

            timer.Start();
        }
        private async Task RunBotAsync()
        {
            #region SETTINGS
            if (!Directory.Exists(SettingsFolder))
            {
                Directory.CreateDirectory(SettingsFolder);
            }
            if (File.Exists(TokenLocation))
            {
                token = File.ReadAllText(TokenLocation);
            }
            else
            {
                File.Create(TokenLocation);
                await LogMessage(new LogMessage(LogSeverity.Warning, "SettingsLoader", "Token not in file."));

                return;
            }
            if (File.Exists(StorageLocation))
            {
                LoadSettings(File.ReadAllText(StorageLocation));
            }
            else
            {
                File.Create(StorageLocation);
                File.WriteAllText(StorageLocation, DefaultSettings);
                LoadSettings(DefaultSettings);
                await LogMessage(new LogMessage(LogSeverity.Warning, "SettingsLoader", "Settings not made, creating file now."));

                return;
            }
            #endregion
            #region Discord Bot Setup
            Instance     = this;
            _client      = new DiscordSocketClient();
            _commands    = new CommandService();
            _services    = new ServiceCollection().AddSingleton(_client).AddSingleton(_commands).BuildServiceProvider();
            _client.Log += LogMessage;
            await RegisterCommandsAsync();

            await _client.LoginAsync(TokenType.Bot, token);

            await _client.StartAsync();

            ConsoleColor temp  = Console.BackgroundColor;
            ConsoleColor temp2 = Console.ForegroundColor;
            Console.BackgroundColor = ConsoleColor.Green;
            Console.ForegroundColor = ConsoleColor.Black;
            Console.WriteLine("Starting...");
            Console.WriteLine("Bot by BlazingFlame#0001, https://github.com/DanielWillett, https://github.com/DanielWillett/SamplePlayercountDiscordBot.");
            Console.Title           = "Sample Playercount Bot";
            Console.BackgroundColor = temp;
            Console.ForegroundColor = temp2;
            #endregion
            #region Timers and Workers
            worker         = new BackgroundWorker();
            worker.DoWork += Worker_DoWork;
            EditTimer      = new TimerService(_client);
            if (EditTimer != null)
            {
                EditTimer.Start();
            }
            else
            {
                await LogMessage(new Discord.LogMessage(LogSeverity.Critical, "EditTimer", "EditTimer is null"));
            }

            if (Settings["MESSAGE_ID"] != "0" && Settings["CHANNEL_ID"] != "0")
            {
                worker.RunWorkerAsync();
            }
            else
            {
                await LogMessage(new LogMessage(LogSeverity.Error, "BkgrWorker", "No message ID has been set, use \"-startplayercount\" to initialize it."));
            }
            #endregion

            await Task.Delay(-1);
        }