Ejemplo n.º 1
0
        public void StartPomodoro()
        {
            if (PomodoroStatus.PomodoroState == PomodoroState.Pomodoro && PomodoroStatus.TimerState == TimerState.Paused) // if paused
            {
                TimerService.Continue();

                PomodoroStatus = new PomdoroStatus()
                {
                    PomodoroState = PomodoroState.Pomodoro,
                    RemainingTime = TimerService.RemainingTime,
                    RunTime       = PomodoroSettings.PomodoroDuration,
                    StartTime     = TimerService.StartTime,
                    TimerState    = TimerState.Running,
                };
            }
            else
            {
                TimerService.Start(PomodoroSettings.PomodoroDuration);

                PomodoroStatus = new PomdoroStatus()
                {
                    PomodoroState = PomodoroState.Pomodoro,
                    RemainingTime = PomodoroSettings.PomodoroDuration,
                    RunTime       = PomodoroSettings.PomodoroDuration,
                    StartTime     = TimerService.StartTime,
                    TimerState    = TimerState.Running,
                };
            }


            StorageService.SaveAppState(PomodoroStatus);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Raised when the client connects to Discord.
        /// <para>
        /// Restarts the <see cref="TimerService"/> and logs that the client has connected.
        /// </para>
        /// </summary>
        /// <returns>No object or value is returned by this method when it completes.</returns>
        private Task ConnectedEventHandler()
        {
            Console.WriteLine($"\n{DateTime.Now}\nCLIENT CONNECTED\n");
            _timer.Start(); // TODO: Remove if it is determined that it is redundant due to ReadyHandler.

            return(Task.CompletedTask);
        }
Ejemplo n.º 3
0
        public GameWindowViewModel(MainWindowViewModel main)
        {
            Main = main;
            var puzzle = Puzzle.FromRowStrings(
                "xxxxx",
                "x...x",
                "x...x",
                "x...x",
                "xxxxx"
                );
            var facade = new PiCrossFacade();

            //timer
            var timeService = ServiceLocator.Current.GetInstance <ITimeService>();

            _start = timeService.Now;

            _timer       = ServiceLocator.Current.GetInstance <ITimerService>();
            _timer.Tick += Timer_Tick;
            _timer.Start(new TimeSpan(0, 0, 0, 0, 100));

            PlayablePuzzle  = facade.CreatePlayablePuzzle(puzzle);
            SquareGrid      = Grid.Create <SquareViewModel>(PlayablePuzzle.Grid.Size, p => new SquareViewModel(PlayablePuzzle.Grid[p]));
            Timer           = "00:00:00";
            CloseGameWindow = new CloseGameWindowCommand(main);
            IsSolved        = new IsSolvedCommand(this);
        }
Ejemplo n.º 4
0
        public LampStateMachine(IMessageService messageService, ITimeService timeService = null, LampState initialState = LampState.Off, ITimerService timer = null)
            : base(initialState)
        {
            this.timeService = timeService ?? new TimeService();
            this.timer       = timer ?? new TimerService();

            timer.Elapsed += (s, a) => this.Fire(LampTrigger.ElapsedTime);

            this.Configure(LampState.Off)
            // .Permit(LampTrigger.PushUp, LampState.On)
            .PermitIf(LampTrigger.PushUp, LampState.On, () => IsOverTime, $"Limit > {TimeLimit}")
            .IgnoreIf(LampTrigger.PushUp, () => !IsOverTime, $"Limit <= {TimeLimit}")
            .Ignore(LampTrigger.PushDown)
            .OnEntry(() => messageService.Send("Dziękujemy za wyłączenie światła"), nameof(messageService.Send));

            this.Configure(LampState.On)
            .OnEntry(() => messageService.Send("Pamiętaj o wyłączeniu światła!"), nameof(messageService.Send))
            .OnEntry(() => timer.Start(), "Start timer")
            .Permit(LampTrigger.PushDown, LampState.Off)
            .PermitIf(LampTrigger.PushUp, LampState.Red, () => !IsOverLimit)
            .PermitIf(LampTrigger.PushUp, LampState.Off, () => IsOverLimit)
            .Permit(LampTrigger.ElapsedTime, LampState.Off)
            .OnExit(() => timer.Stop());


            this.Configure(LampState.Red)
            .OnEntry(() => redCounter++)
            .Permit(LampTrigger.PushUp, LampState.On)
            .Permit(LampTrigger.PushDown, LampState.Off);


            this.OnTransitioned(t => Console.WriteLine($"{t.Source} -> {t.Destination}"));
            this.timer = timer;
        }
Ejemplo n.º 5
0
        public void OnGameModeInit(IWorldService worldService, IEntityManager entityManager,
                                   INativeObjectProxyFactory proxyFactory, ITimerService timerService)
        {
            // Only test FastNative performance if FastNative is not activated
            if (proxyFactory is FastNativeBasedNativeObjectProxyFactory)
            {
                return;
            }

            // Benchmarking
            var fastFactory = new FastNativeBasedNativeObjectProxyFactory(_client);
            var fastProxy   = (TestingFastNative)fastFactory.CreateInstance(typeof(TestingFastNative));

            _fastProxy = fastProxy;
            _nativeGetVehicleParamsEx = Interop.FastNativeFind("GetVehicleParamsEx");
            _testVehicleId            = worldService.CreateVehicle(VehicleModelType.BMX, Vector3.One, 0, 0, 0).Entity.Handle;
            //timerService.Start(_ => BenchmarkRunTimer(), TimeSpan.FromSeconds(2));
            timerService.Start(_ => BenchmarkRunTimerProxy(), TimeSpan.FromSeconds(2));

            // Test native features
            Console.WriteLine("TEST WITH HANDLE FACTORY:");
            // RunTests(proxyFactory);
            Console.WriteLine("TEST WITH FAST FACTORY:");
            RunTests(fastFactory);

            // Threading test
            // timerService.Start(_ => ThreadingTest(fastProxy, handleProxy), TimeSpan.FromSeconds(15));

            // Multiple calls test
            InvokeVehicleNatives(entityManager, fastProxy);

            GetNetworkStats(out string x, 500);
            Console.WriteLine(x);
        }
Ejemplo n.º 6
0
        public ShellPageViewModel(
            IUserSettings userSettings,
            ITimerService timer,
            ITelemetry telemetry,
            ISystemInfoProvider systemInfoProvider)
        {
            Guard.IsNotNull(userSettings, nameof(userSettings));
            Guard.IsNotNull(timer, nameof(timer));
            Guard.IsNotNull(telemetry, nameof(telemetry));

            _userSettings = userSettings;
            _ratingTimer  = timer;
            _telemetry    = telemetry;

            _userSettings.SettingSet += OnSettingSet;

            var lastDismissDateTime = _userSettings.GetAndDeserialize <DateTime>(UserSettingsConstants.RatingDismissed);

            if (!systemInfoProvider.IsFirstRun() &&
                !systemInfoProvider.IsTenFoot() &&
                !_userSettings.Get <bool>(UserSettingsConstants.HasRated) &&
                lastDismissDateTime.AddDays(7) <= DateTime.UtcNow)
            {
                _ratingTimer.Interval         = 1800000; // 30 minutes
                _ratingTimer.IntervalElapsed += OnIntervalLapsed;
                _ratingTimer.Start();
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Starts a timer with the specified <paramref name="interval"/>. The specified <paramref name="method"/> will be invoked on the specified <paramref name="target"/> each timer tick.
        /// </summary>
        /// <param name="timerService">The timer service.</param>
        /// <param name="target">The target on which to tick.</param>
        /// <param name="method">The method to invoke each timer tick.</param>
        /// <param name="interval">The interval at which to tick.</param>
        /// <returns>A reference to the started timer.</returns>
        public static TimerReference Start(this ITimerService timerService, object target, MethodInfo method, TimeSpan interval)
        {
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }
            if (method == null)
            {
                throw new ArgumentNullException(nameof(method));
            }

            if (!TimerSystem.IsValidInterval(interval))
            {
                throw new ArgumentOutOfRangeException(nameof(interval), interval, "The interval should be a nonzero positive value.");
            }

            if (!method.DeclaringType.IsInstanceOfType(target))
            {
                throw new ArgumentException("The specified method is not a member of the specified target", nameof(method));
            }

            var parameterInfos = method.GetParameters()
                                 .Select(info => new MethodParameterSource(info)
            {
                IsService = true
            })
                                 .ToArray();

            var compiled = MethodInvokerFactory.Compile(method, parameterInfos);

            return(timerService.Start(serviceProvider => compiled(target, null, serviceProvider, null), interval));
        }
Ejemplo n.º 8
0
 private void Start()
 {
     if (CanStart())
     {
         TimerDuration = _timerService.Start(new TimeSpan(TimerDuration.Hours, TimerDuration.Minutes, TimerDuration.Seconds));
     }
 }
Ejemplo n.º 9
0
 public void Sort(IList <int> list)
 {
     Console.WriteLine("******Heap Sort*******");
     _timer.Start();
     Sort(list, list.Count);
     Console.WriteLine("Time taken to sort using heap sort = " + _timer.GetTimerValue() + " MilliSeconds");
 }
Ejemplo n.º 10
0
 public void Sort(IList <int> list)
 {
     Console.WriteLine("******Merge Sort*******");
     _timer.Start();
     Sort(list, new int[list.Count], 0, list.Count - 1);
     Console.WriteLine("Time taken to sort using merge sort = " + _timer.GetTimerValue() + " MilliSeconds");
 }
Ejemplo n.º 11
0
 public Task <int> OnExecute()
 {
     if (double.TryParse(Time, out var time) && time > 0)
     {
         timer.Start(time);
     }
     return(Task.FromResult(0));
 }
Ejemplo n.º 12
0
 public void Start(String destination)
 {
     _destination = destination;
     if (_timerToken == null)
     {
         _timerToken = _timerService.Start(TimeSpan.FromMilliseconds(1000), Do);
     }
 }
Ejemplo n.º 13
0
        public CyrillicString(ITimerService timerService, IRandomService randomService)
        {
            _timerService  = timerService;
            _randomService = randomService;
            var milliseconds = _randomService.RandomInt(500, 1000);

            _timerService.Start(TimeSpan.FromMilliseconds(milliseconds), RefreshString);
        }
Ejemplo n.º 14
0
        public override Task Initialize()
        {
            timerService.Interval = TimeSpan.FromSeconds(1);
            timerService.Tick += Timer_Tick;
            timerService.Start();

            return Task.CompletedTask;
        }
Ejemplo n.º 15
0
 public ParkingService(bool IsStartTimer)
 {
     if (IsStartTimer)
     {
         WithdrawTimer = new TimeService();
         WithdrawTimer.Start();
     }
     LogFileService = new LogService(Settings.LogPath);
 }
 public TopClothesService(IServiceScopeFactory factory, ITimerService timer)
 {
     _scopeFactory   = factory;
     _timer          = timer;
     _timer.Elapsed += Service_Elapsed;
     _timer.Interval = 30000;
     _timer.Start();
     Service_Elapsed(this, null);
 }
Ejemplo n.º 17
0
        public void StartPomodoro()
        {
            // check if paused
            if (PomodoroStatus.PomodoroState == PomodoroState.Pomodoro &&
                PomodoroStatus.TimerState == TimerState.Paused)
            {
                PomodoroStatus = PomodoroTimerState.Pomodoro(PomodoroStatus.RunTime, PomodoroStatus.RemainingRunTime);
            }
            else
            {
                // start new pomodoro
                PomodoroStatus = PomodoroTimerState.Pomodoro(PomodoroSettings.PomodoroDuration, PomodoroSettings.PomodoroDuration);
            }

            TimerService.Start(PomodoroStatus.RemainingTime);
            StorageService.SaveAppState(PomodoroStatus);
            PomodoroTimerStateChangedEvent?.Invoke(this, new PomodoroTimerStateChangedEventArgs(PomodoroStatus));
            LogState("StartPomodoro");
        }
Ejemplo n.º 18
0
 internal NotificationReporter(ITimeService timeService, ITimerService timerService)
 {
     _notificationList      = new ObservableCollection <Notification>();
     _notificationObs       = new ReadOnlyObservableCollection <Notification>(_notificationList);
     _timeService           = new UniqueTimeService(timeService);
     _timerService          = timerService;
     _timerService.TimeSpan = TimeSpan.FromSeconds(1);
     ExpirationTime         = TimeSpan.FromSeconds(25);
     LifeTime = TimeSpan.FromDays(7);
     _timerService.Elapsed += TimerServiceElapsed;
     _timerService.Start();
 }
Ejemplo n.º 19
0
 /// <summary>
 /// 計測を開始する
 /// </summary>
 public void Start()
 {
     if (Status == StopwatchStatus.Stoped)
     {
         _beginDateTime       = _timeService.Now;
         _previousLapDateTime = _beginDateTime;
         Status = StopwatchStatus.Running;
         _timerService.Start();
     }
     else if (Status == StopwatchStatus.Paused)
     {
         _beginDateTime       = _timeService.Now;
         _previousLapDateTime = _beginDateTime;
         Status = StopwatchStatus.Running;
         _timerService.Start();
     }
     else
     {
         throw new InvalidOperationException($"Stopwatch status is {Status}.");
     }
 }
Ejemplo n.º 20
0
        public void Run()
        {
            if (mCurrentState == ExerciseServiceState.Stopped)
            {
                mTimerService.Start(TIMER_INTERVAL_MS);
            }
            else if (mCurrentState == ExerciseServiceState.Paused)
            {
                mTimerService.Resume();
            }

            ChangeState(ExerciseServiceState.Started);
        }
Ejemplo n.º 21
0
        public bool StartApp(string action)
        {
            var commandLine = Console.ReadLine();

            var commandArray = commandLine?.Split(' ');

            action = commandArray.FirstOrDefault();

            var result = true;

            switch (action?.ToLower())
            {
            case "create_product":
                Console.WriteLine(_productService.CreateProduct(commandArray));
                break;

            case "get_product_info":
                Console.WriteLine(_productService.GetProductInfo(commandArray));
                result = _campaignService.IsExistActiveCampaign();
                break;

            case "create_campaign":
                Console.WriteLine(_campaignService.CreateCampaign(commandArray));
                _timerService.Start();
                result = _campaignService.IsExistActiveCampaign();
                break;

            case "get_campaign_info":
                Console.WriteLine(_campaignService.GetCampaignInfo(commandArray));
                result = _campaignService.IsExistActiveCampaign();
                break;

            case "increase_time":
                Console.WriteLine(_appTimeService.IncreaseTime(commandArray));
                result = _campaignService.IsExistActiveCampaign();
                break;

            case "exit":
                _timerService.End();
                Console.WriteLine("bye bye");
                result = false;
                break;

            default:
                Console.WriteLine("Incorrect command usage!");
                break;
            }

            return(result);
        }
Ejemplo n.º 22
0
 public PlayerManager(IDataService dataService,
                      IPlayerService playerService,
                      ISettingsService settingsService,
                      IEventAggregator eventAggregator,
                      ITimerService timerService)
 {
     _dataService                = dataService;
     _playerService              = playerService;
     _settingsService            = settingsService;
     _eventAggregator            = eventAggregator;
     _timerService               = timerService;
     _timerService.TimerElapsed += OnTimerElapsed;
     _timerService.Start();
     _playerService.AudioPlayerStateChanged += OnAudioPlayerStateChanged;
     _playerService.MediaStateChanged       += OnMediaStateChanged;
 }
Ejemplo n.º 23
0
        public ParkingService(ITimerService withdrawTimer, ITimerService logTimer, ILogService logService)
        {
            parking = Parking.GetInstance;

            _withdrawTimer = withdrawTimer;
            _logTimer      = logTimer;
            _logService    = logService;

            _withdrawTimer.Interval = Settings.WithdrawTime * SecToMilisec;
            _withdrawTimer.Elapsed += Withdraw;
            _logTimer.Interval      = Settings.LogTime * SecToMilisec;
            _logTimer.Elapsed      += Log;

            _withdrawTimer.Start();
            _logTimer.Start();
        }
Ejemplo n.º 24
0
        public TeamStatisticsViewModel(ITeamClient teamClient, IStatisticsClient statisticsClient, ITimerService timerService, IEventAggregator eventAggregator, ICacheService cacheService)
        {
            _teamClient = teamClient;
            _statisticsClient = statisticsClient;
            timerService.Start(TimeSpan.FromSeconds(10), OnRefresh);
            _eventAggregator = eventAggregator;
            _cacheService = cacheService;

            Func<Boolean> canExecute = () =>
            {
                var password = new NetworkCredential(string.Empty, TeamPassword).Password;
                return !String.IsNullOrWhiteSpace(TeamName) && !TeamName.Contains(" ") &&
                       !String.IsNullOrWhiteSpace(password) && !password.Contains(" ");
            };

            AcceptExistingTeamCommand = new RelayCommand(OnAcceptExistingTeam, canExecute);
            CreateNewTeamCommand = new RelayCommand(OnCreateNewTeam, canExecute);
        }
Ejemplo n.º 25
0
        public void OnGameModeInit(ITimerService timerService)
        {
            _stopwatch1.Start();
            _stopwatch2.Start();

            TimerReference timer = null;

            timer = timerService.Start(_ =>
            {
                if (++_readonlyTicks == 3)
                {
                    Console.WriteLine("Stop timer");
                    timerService.Stop(timer);
                }
                Console.WriteLine($"Manual timer {_stopwatch2.Elapsed}");
                _stopwatch2.Restart();
            }, TimeSpan.FromSeconds(0.1));
        }
Ejemplo n.º 26
0
        private void StartCountdown()
        {
            _timer.Start(TimeSpan.FromSeconds(1), () =>
            {
                if (!IsTracking)
                {
                    return(false);
                }

                TimeLeft = _timeEnd - DateTime.Now;

                if (TimeLeft < TimeSpan.FromSeconds(0))
                {
                    StopTracking();
                }

                return(IsTracking);
            });
        }
Ejemplo n.º 27
0
        public MainWindowViewModel()
        {
            var diContainer = new UnityContainer();

            diContainer.RegisterType <ITimerService, TimerService>(new ContainerControlledLifetimeManager());
            diContainer.RegisterType <IRandomService, RandomService>(new ContainerControlledLifetimeManager());
            diContainer.RegisterType <ICoreService, CoreService>();
            diContainer.RegisterType <ISampleGenerationService, SampleGenerationService>();

            _offline             = CreateCyrillicString(diContainer, "OFFLINE", "ОФФЛИНЕ");
            _online              = CreateCyrillicString(diContainer, "ONLINE", "ОНЛИНЕ");
            _title               = CreateCyrillicString(diContainer, "Dusty Drones Sensor StreamService Configuration Dashboard", "Дусты Дронес Сенсор СтреамСервице Цонфигуратион Дашбоард");
            _fileTitle           = CreateCyrillicString(diContainer, "Test Interface For File/Binary Based Listeners", "Тест Интерфаце Фор Филе/Бинары Басед Листенерс");
            _fileStatus          = _offline;
            _webTitle            = CreateCyrillicString(diContainer, "Test Interface For Web/HTTP Based Listeners", "Тест Интерфаце Фор Үеб/HТТП Басед Листенерс");
            _webStatus           = _offline;
            _footer1             = CreateCyrillicString(diContainer, "DDSSCD v0.13.267.9782964387", "ДДССЦД в0.13.267.9782964387");
            _footer2             = CreateCyrillicString(diContainer, "DDSSCD is connected to the service backend", "ДДССЦД ис цоннецтед то тhе сервице бацкенд");
            _outputPath          = CreateCyrillicString(diContainer, "Output Path", "Оутпут Патh");
            _outputHttp          = CreateCyrillicString(diContainer, "Output HTTP", "Оутпут HТТП");
            _fileSamplesReceived = CreateCyrillicString(diContainer, "No samples received", "Но самплес рецеивед");
            _webSamplesReceived  = CreateCyrillicString(diContainer, "No samples received", "Но самплес рецеивед");

            _timerService = diContainer.Resolve <ITimerService>();
            _timerService.Start(TimeSpan.FromMilliseconds(50), RefreshBullShit);

            _coreFileService = diContainer.Resolve <ICoreService>(new DependencyOverride <IOutputService>(new FileOutputService()));
            _coreFileService.SampleReceived += coreFileService_SampleReceived;
            _coreHttpService = diContainer.Resolve <ICoreService>(new DependencyOverride <IOutputService>(new HttpOutputService()));
            _coreHttpService.SampleReceived += coreHttpService_SampleReceived;

            Observable.FromEventPattern(x => this.PathOutputChanged += x, x => this.PathOutputChanged -= x)
            .Throttle(TimeSpan.FromMilliseconds(1000))
            .ObserveOnDispatcher()
            .Do(x => RefreshOutput())
            .Subscribe();
            Observable.FromEventPattern(x => this.HttpOutputChanged += x, x => this.HttpOutputChanged -= x)
            .Throttle(TimeSpan.FromMilliseconds(1000))
            .ObserveOnDispatcher()
            .Do(x => RefreshOutput())
            .Subscribe();
        }
Ejemplo n.º 28
0
        public async Task OnTheHour_ASilentPushNotificationShouldBeSent(int hour, int minutes, int seconds, bool onHour)
        {
            _sut = new TimerService(_timerClock, _clock.Object, _mediator.Object, _ledBoard.Object,
                                    _timerEvents.Object, _lightsController.Object, _relayBoard.Object);

            _clock.Setup(x => x.Now).Returns(new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day,
                                                          hour, minutes, seconds));

            _sut.Start();

            await Task.Delay(2.Seconds());

            if (onHour)
            {
                _mediator.Verify(x => x.Send(It.IsAny <PushNotificationCommand>(), CancellationToken.None), Times.AtLeastOnce);
            }
            else
            {
                _mediator.Verify(x => x.Send(It.IsAny <PushNotificationCommand>(), CancellationToken.None), Times.Never);
            }
        }
Ejemplo n.º 29
0
        public async Task Every5Seconds_TheRingDoorbellShouldBePolled(int hour, int minutes, int seconds, bool on5Seconds)
        {
            _sut = new TimerService(_timerClock, _clock.Object, _mediator.Object, _ledBoard.Object,
                                    _timerEvents.Object, _lightsController.Object, _relayBoard.Object);

            _clock.Setup(x => x.Now).Returns(new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day,
                                                          hour, minutes, seconds));

            _sut.Start();

            await Task.Delay(2.Seconds());

            if (on5Seconds)
            {
                _mediator.Verify(x => x.Publish(It.IsAny <PollDoorbellMotionCommand>(), CancellationToken.None), Times.AtLeastOnce);
            }
            else
            {
                _mediator.Verify(x => x.Publish(It.IsAny <PollDoorbellMotionCommand>(), CancellationToken.None), Times.Never);
            }
        }
        public BotDeploymentViewModel(IArenaClient arenaClient, IBotClient botClient, IDeploymentClient deploymentClient, IScriptClient scriptClient, IEventAggregator eventAggregator, IFileExplorerService fileExplorerService, IFileService fileService, ITimerService timerService, ICacheService cacheService)
        {
            _arenaClient         = arenaClient;
            _botClient           = botClient;
            _deploymentClient    = deploymentClient;
            _scriptClient        = scriptClient;
            _eventAggregator     = eventAggregator;
            _fileExplorerService = fileExplorerService;
            _fileService         = fileService;
            _cacheService        = cacheService;

            timerService.Start(TimeSpan.FromSeconds(5), RefreshArenas);

            SubscribeEvents(eventAggregator);

            SaveScriptCommand        = new RelayCommand(OnSaveScript);
            LoadScriptCommand        = new RelayCommand(OnLoadScript);
            ValidateBotScriptCommand = new RelayCommand(OnValidateBotScript);
            DeployBotCommand         = new RelayCommand(OnDeployBot,
                                                        () => SelectedArena != null && ScriptValid && (TimeUntilNextAllowedDeployment <= TimeSpan.Zero && (BotPhysicalHealth + BotStamina <= SelectedArena.MaximumPoints) /*|| CurrentTeam.Predator*/));
        }