public BaseExerciseController(IExerciseModel exerciseModel, IExerciseView exerciseView, IExerciseBackgroundView exerciseBackgroundView, IExerciseHUD hud, ITimerFactory timerFactory,
                                      IExerciseTerminator terminator, ILogger logger, ISoundManager soundManager) : base(logger, terminator, exerciseView)
        {
            _soundManager   = soundManager;
            _model          = exerciseModel;
            _backgroundView = exerciseBackgroundView;
            _hud            = hud;

            _timeoutTimer         = timerFactory.CreateTimer();
            _exerciseTimer        = timerFactory.CreateTimer();
            _botTimer             = timerFactory.CreateTimer();
            _botTimer.OnComplete += ProcessBotAnswer;

            _tutorialManager           = new TutorialManager(_model, _view, _model.ExerciseConfiguration);
            _tutorialManager.OnUpdate += OnTutorialUpdate;

            _tutorialActivityManager = new TutorialActivityManager(logger, 3, 2, exerciseModel.ExerciseInitVO.StartWithTutorial, exerciseModel.ExerciseInitVO.TutorialSystemEnabled);

            var exerciseSettings = _model.ExerciseSettings;

            _view.Settings     = exerciseSettings;
            _soundManager.Mute = exerciseSettings.ContainsKey(ExerciseSettingsEnum.SoundsEnabled) && !exerciseSettings[ExerciseSettingsEnum.SoundsEnabled];

            MapState(BaseStates.INIT, OnStateInit, AfterStateInit);

            _botActived = false;

            _stopped = false;
        }
        public FlashGlanceController(IExerciseModel exerciseModel, IExerciseView exerciseView, IExerciseBackgroundView exerciseBackgroundView, IExerciseHUD hud, ITimerFactory timerFactory, IExerciseTerminator terminator, ILogger logger, ISoundManager soundManager) : base(exerciseModel, exerciseView, exerciseBackgroundView, hud, timerFactory, terminator, logger, soundManager)
        {
            _random = new Random();

            _spawnTimer             = timerFactory.CreateTimer();
            _spawnTimer.OnComplete += RequestNewItem;

            _moveTimer             = timerFactory.CreateTimer();
            _moveTimer.OnComplete += RequestMovement;

            _switchTimer             = timerFactory.CreateTimer();
            _switchTimer.OnComplete += RequestSwap;
        }
        public void ShouldConfigureTimersUponInitialization()
        {
            var elapsedTimer     = Substitute.For <ITimer>();
            var elapsedCostTimer = Substitute.For <ITimer>();

            _timerFactoryMock.CreateTimer().Returns(elapsedTimer, elapsedCostTimer);
            new ActiveRentalSessionViewModel(_timerFactoryMock, _rentalServiceMock, _dialogServiceMock,
                                             _messengerServiceMock);
            Assert.AreEqual(elapsedTimer.Interval.ToString(), TimeSpan.FromSeconds(1).ToString());
            Assert.AreEqual(elapsedCostTimer.Interval.ToString(), TimeSpan.FromSeconds(60).ToString());
        }
        /// <inheritdoc />
        public async Task StartAsync(CancellationToken cancellationToken = default)
        {
            IsRunning = true;
            webSocket = gatewayUtilsFactory.CreateWebSocketClient();

            var cancellationTokenSource = new CancellationTokenSource();
            await rxWorker.Start(this);

            await txWorker.Start(this, webSocket);

            worker = timerFactory.CreateTimer(Run, 0, WorkerThreadName);
            worker.StopOnException  = true;
            worker.OnUnexpectedStop = () => Restart();
            await worker.Start();
        }
Exemple #5
0
 public RssPlugin(IBitTorrentEngine torrentEngine, IDataRepository dataRepository, ITimerFactory timerFactory, IWebClient webClient)
 {
     _torrentEngine = torrentEngine;
     _dataRepository = dataRepository;
     _timer = timerFactory.CreateTimer();
     _webClient = webClient;
 }
        public bool triggers_on_path_too_big(int threshold)
        {
            ITimerFactory timerFactory = Substitute.For <ITimerFactory>();
            ITimer        timer        = Substitute.For <ITimer>();

            timerFactory.CreateTimer(Arg.Any <TimeSpan>()).Returns(timer);

            string      path       = "path";
            IFileSystem fileSystem = Substitute.For <IFileSystem>();

            IFileInfo[] files = new[]
            {
                GetFile(10),
                GetFile(100),
                GetFile(200)
            };
            fileSystem.Directory.Exists(path).Returns(true);
            fileSystem.DirectoryInfo.FromDirectoryName(path).EnumerateFiles().Returns(files);

            bool triggered = false;

            PathSizePruningTrigger trigger = new(path, threshold, timerFactory, fileSystem);

            trigger.Prune += (o, e) => triggered = true;

            timer.Elapsed += Raise.Event();
            return(triggered);
        }
Exemple #7
0
        public void OnTaskError_TaskManagerOnTaskErrorEventMustBeCalled()
        {
            Exception exception = new Exception();

            IDateTimeProvider dateTimeProvider = Substitute.For <IDateTimeProvider>();

            TaskCofiguration taskCofiguration = new TaskCofiguration(1, "Task1", 10, true, true, false);
            ITask            task             = Substitute.For <ITask>();

            task.WhenForAnyArgs(x => x.Run()).Do(
                x =>
            {
                throw exception;
            });
            ITimerFactory timerFactory = Substitute.For <ITimerFactory>();
            ITimer        timer        = new TimerStub(DateTime.UtcNow);

            timerFactory.CreateTimer(1).ReturnsForAnyArgs(timer);

            TaskDefinition taskDefinition = new TaskDefinition(task, taskCofiguration);
            TaskManager    taskManager    = new TaskManager(new List <TaskDefinition> {
                taskDefinition
            }, timerFactory, dateTimeProvider);

            taskManager.OnTaskError += (sender, args) => Assert.AreEqual(exception, args.Error);

            taskManager.Start();
        }
        public NodeStatsManager(ITimerFactory timerFactory, ILogManager logManager, int maxCount = 10000)
        {
            _maxCount = maxCount;
            _logger   = logManager?.GetClassLogger() ?? throw new ArgumentNullException(nameof(logManager));

            _cleanupTimer          = timerFactory.CreateTimer(TimeSpan.FromMinutes(10));
            _cleanupTimer.Elapsed += CleanupTimerOnElapsed;
            _cleanupTimer.Start();
        }
        public TimedEvent(ITimerFactory timer, int intervalInMilliseconds, Action action, bool runOnce)
        {
            this.timer   = timer.CreateTimer(intervalInMilliseconds);
            this.action  = action ?? throw new ArgumentNullException(nameof(action));
            this.runOnce = runOnce;

            this.timer.Elapsed += Timer_Elapsed;
            this.timer.Start();
        }
 public DiskFreeSpacePruningTrigger(string path, long threshold, ITimerFactory timerFactory, IFileSystem fileSystem)
 {
     _path           = path;
     _threshold      = threshold;
     _fileSystem     = fileSystem;
     _timer          = timerFactory.CreateTimer(_defaultCheckInterval);
     _timer.Elapsed += OnTick;
     _timer.Start();
 }
        /// <inheritdoc />
        public async Task Start(IGatewayService gateway, IClientWebSocket webSocket)
        {
            IsRunning      = true;
            this.webSocket = webSocket;

            timer = timerFactory.CreateTimer(Run, 0, WorkerThreadName);
            timer.StopOnException  = true;
            timer.OnUnexpectedStop = () => gateway.Restart();
            await timer.Start();
        }
Exemple #12
0
        /// <inheritdoc />
        public async Task Start(IGatewayService gateway)
        {
            this.gateway = gateway;
            IsRunning    = true;

            stream = gatewayUtilsFactory.CreateStream();
            worker = timerFactory.CreateTimer(Run, 0, WorkerThreadName);
            worker.StopOnException  = true;
            worker.OnUnexpectedStop = () => gateway.Restart();
            await worker.Start();
        }
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="path">The path to watch.</param>
        /// <param name="threshold">Threshold in bytes that if exceeded by <see cref="path"/> will trigger full pruning.</param>
        /// <param name="timerFactory">Factory for timers.</param>
        /// <param name="fileSystem">File system access.</param>
        /// <exception cref="ArgumentException">Thrown if <see cref="path"/> doesn't exist.</exception>
        public PathSizePruningTrigger(string path, long threshold, ITimerFactory timerFactory, IFileSystem fileSystem)
        {
            if (!fileSystem.Directory.Exists(path))
            {
                throw new ArgumentException($"{path} is not a directory", nameof(path));
            }

            _path           = path;
            _threshold      = threshold;
            _fileSystem     = fileSystem;
            _timer          = timerFactory.CreateTimer(_defaultCheckInterval);
            _timer.Elapsed += OnTick;
            _timer.Start();
        }
        public PeriodicBundleTrigger(ITimerFactory timerFactory, TimeSpan interval, IBlockTree blockTree, ILogger logger)
        {
            _blockTree = blockTree;
            _logger    = logger;

            _timer = timerFactory.CreateTimer(interval);

            _timer.Elapsed += TimerOnElapsed;
            _timer.Start();

            if (_logger.IsInfo)
            {
                _logger.Info("Period bundle trigger initialized");
            }
        }
Exemple #15
0
        private void InitTaskRunner(IList <TaskDefinition> taskDefinitions)
        {
            m_TaskRunners = new List <ITaskRunner>(taskDefinitions.Count);

            for (int i = 0; i < taskDefinitions.Count; i++)
            {
                TaskDefinition   taskDefinition   = taskDefinitions[i];
                TaskCofiguration taskCofiguration = taskDefinition.Configuration;
                ITimer           timer            = m_TimerFactory.CreateTimer(taskCofiguration.Seconds * 1000);

                ITaskRunner taskRunner = new TaskRunner(taskDefinition.Task, taskCofiguration.TaskId, m_DateTimeProvider, timer, taskCofiguration.Enabled, taskCofiguration.StopOnError, taskCofiguration.RunOnlyOnce);

                taskRunner.OnTaskError  += TaskRunnerOnTaskError;
                taskRunner.TaskEnded    += TaskRunnerAfterTaskEnded;
                taskRunner.TaskStarting += TaskRunnerBeforeTaskStarted;

                TaskRunners.Add(taskRunner);
            }
        }
            public async Task StopShouldStopTheHeartbeat(
                ITimer heartbeat,
                [Frozen, Substitute] ITimerFactory timerFactory,
                [Frozen, Substitute] IGatewayTxWorker txWorker,
                [Frozen, Substitute] IGatewayUtilsFactory factory,
                [Target] DefaultGatewayService gateway
                )
            {
                var cancellationToken = new CancellationToken(false);

                timerFactory.CreateTimer(Any <AsyncTimerCallback>(), Any <int>(), Is("Heartbeat")).Returns(heartbeat);

                await gateway.StartAsync();

                await gateway.StartHeartbeat(10);

                await gateway.StopAsync();

                await heartbeat.Received().Stop();
            }
Exemple #17
0
        public void Start()
        {
            IDateTimeProvider dateTimeProvider = Substitute.For <IDateTimeProvider>();

            TaskCofiguration taskCofiguration = new TaskCofiguration(1, "Task1", 10, true, true, false);
            ITask            task             = Substitute.For <ITask>();
            ITimerFactory    timerFactory     = Substitute.For <ITimerFactory>();
            ITimer           timer            = Substitute.For <ITimer>();

            timerFactory.CreateTimer(1).ReturnsForAnyArgs(timer);

            TaskDefinition taskDefinition = new TaskDefinition(task, taskCofiguration);
            TaskManager    taskManager    = new TaskManager(new List <TaskDefinition> {
                taskDefinition
            }, timerFactory, dateTimeProvider);

            taskManager.Start();

            timer.Received(1).Start();
        }
Exemple #18
0
        public ItemMonitor(InventoryApiContext context, ITimerFactory TimerFactory, ILoggerFactory loggerFactory)
        {
            //initialize private variables
            _context        = context;
            TimerReferences = new Dictionary <string, Timer>();
            _timerFactory   = TimerFactory;
            _logger         = loggerFactory.CreateLogger <ItemMonitor>();

            //run periodic monitoring addition weekly
            _scheduleFromContextReRunInterval = new TimeSpan(7, 0, 0, 0);

            //the timer task will be scheduled to run weekly, but get set
            //timers for any expirations dates within 9 days so the timer
            //will be rerun before the covered window expires
            _taskScheduleLimit = _scheduleFromContextReRunInterval + new TimeSpan(2, 0, 0, 0);

            //schedule recurring item monitor, which will schedule expiration task for each item about to expire
            _scheduledRunFromContextTimer = _timerFactory.CreateTimer(x =>
            {
                ScheduleFromContext();
            }, null, _taskScheduleLimit, _scheduleFromContextReRunInterval);
        }
        public void should_remove_excessive_stats()
        {
            ITimerFactory timerFactory = Substitute.For <ITimerFactory>();
            ITimer        timer        = Substitute.For <ITimer>();

            timerFactory.CreateTimer(Arg.Any <TimeSpan>()).Returns(timer);

            var manager = new NodeStatsManager(timerFactory, LimboLogs.Instance, 3);
            var nodes   = TestItem.PublicKeys.Take(3).Select(k => new Node(k, new IPEndPoint(IPAddress.Loopback, 30303))).ToArray();

            manager.ReportSyncEvent(nodes[0], NodeStatsEventType.SyncStarted);
            manager.ReportSyncEvent(nodes[1], NodeStatsEventType.SyncStarted);
            manager.ReportSyncEvent(nodes[2], NodeStatsEventType.SyncStarted);
            Node removedNode = new Node(TestItem.PublicKeyD, IPEndPoint.Parse("192.168.0.4:30303"));

            manager.ReportHandshakeEvent(removedNode, ConnectionDirection.In);
            manager.GetCurrentReputation(removedNode).Should().NotBe(0);

            timer.Elapsed += Raise.Event();

            manager.GetCurrentReputation(removedNode).Should().Be(0);
            nodes.Select(n => manager.GetCurrentReputation(n)).Should().NotContain(0);
        }
        public bool triggers_on_low_free_space(int availableFreeSpace)
        {
            ITimerFactory timerFactory = Substitute.For <ITimerFactory>();
            ITimer        timer        = Substitute.For <ITimer>();

            timerFactory.CreateTimer(Arg.Any <TimeSpan>()).Returns(timer);

            string      path       = "path";
            IFileSystem fileSystem = Substitute.For <IFileSystem>();

            fileSystem.Path.GetFullPath(path).Returns(path);
            fileSystem.Path.GetPathRoot(path).Returns(path);
            fileSystem.DriveInfo.FromDriveName(path).AvailableFreeSpace.Returns(availableFreeSpace);

            bool triggered = false;

            DiskFreeSpacePruningTrigger trigger = new(path, 1000, timerFactory, fileSystem);

            trigger.Prune += (o, e) => triggered = true;

            timer.Elapsed += Raise.Event();
            return(triggered);
        }
Exemple #21
0
        //Schedule the item passed in for expiration
        public void ScheduleExpiration(Items item)
        {
            //the timespan between the item expiration and now
            TimeSpan timeSpan = item.Expiration.Subtract(DateTime.Now);

            //if the item has already expired, schedule immediately
            if (timeSpan.Ticks < 0)
            {
                timeSpan = new TimeSpan(0);
            }
            //if a timer has not already been set for this item
            if (!TimerReferences.ContainsKey(item.Label))
            {
                //do not schedule for item too far in advance
                if (timeSpan <= _taskScheduleLimit)
                {
                    //schedule one-time timer and preserve reference in Dictionary
                    TimerReferences.Add(item.Label, _timerFactory.CreateTimer(x =>
                    {
                        ItemExpired((Items)x);
                    }, item, timeSpan, new TimeSpan(0, 0, 0, 0, -1)));
                }
            }
        }
Exemple #22
0
 public SchedulerEntry(T entity, long period, TimerCallback timerCallback, bool autoStart, ITimerFactory timerFactory)
 {
     Entity  = entity;
     _period = period;
     Timer   = timerFactory.CreateTimer(timerCallback, this, autoStart ? period : Timeout.Infinite, Timeout.Infinite);
 }
Exemple #23
0
 /// <inheritdoc />
 public async Task StartAsync(CancellationToken cancellationToken)
 {
     cancellationToken.ThrowIfCancellationRequested();
     timer = timerFactory.CreateTimer(Run, options.PollingInterval, nameof(DefaultRequestWorker));
     await timer.Start();
 }