Stops the timing by setting to .
void OnPauseExecute() { if (RecorderState == RecorderState.Paused) { _systemTray.HideNotification(); _recorder.Start(); _timing?.Start(); _timer?.Start(); RecorderState = RecorderState.Recording; Status.LocalizationKey = nameof(LanguageManager.Recording); } else { _recorder.Stop(); _timer?.Stop(); _timing?.Pause(); RecorderState = RecorderState.Paused; Status.LocalizationKey = nameof(LanguageManager.Paused); _systemTray.ShowTextNotification(Loc.Paused, null); } }
public void Stop() { try { Logger.WriteDebug(MethodBase.GetCurrentMethod(), "Stopping"); var _stopWatch = new Stopwatch(); _stopWatch.Start(); unregisterEvents(); _receiveMailTaskMonitorTimer?.Stop(); _receiveMailTaskTokenSource?.Cancel(); _stopWatch.Stop(); Logger.WriteDebug(MethodBase.GetCurrentMethod(), $"Stopped -> {_stopWatch.Elapsed}"); } catch (Exception ex) { ExceptionOccured.RaiseEvent(this, new ExceptionEventArgs { Methode = MethodBase.GetCurrentMethod(), Error = ex }); } finally { IsRunning = false; } }
// Handles the subscriber's MetaDataReceived event. private void DataSubscriber_MetaDataReceived(object sender, EventArgs <DataSet> e) { List <string> songs; DataTable deviceTable; // Stop the timeout timer because the connection was successful. m_timeoutTimer?.Stop(); m_metadata = e.Argument; deviceTable = m_metadata.Tables["DeviceDetail"]; // Get the song list from the metadata. if (deviceTable != null) { songs = deviceTable.Rows.Cast <DataRow>() .Where(row => row["Enabled"].ToNonNullString("0").ParseBoolean()) .Select(row => row["Acronym"].ToNonNullString()).ToList(); //.Where(row => row["ProtocolName"].ToNonNullString() == "Wave Form Input Adapter") OnGotSongList(songs); } // Set playback state to connected. OnStateChanged(PlaybackState.Connected); }
internal async Task GotoChildSlide(BSCarouselItem item) { _transitionTimer?.Stop(); var slide = Children.IndexOf(item); if (ClickLocked) { Callback.Add(item); return; } if (!Children.Contains(item)) { return; } var back = slide < _active; if (slide == _active) { return; } ClickLocked = true; _last = _active; _active = slide; await Children[_last].InternalHide(); await Children[_active].InternalShow(); await DoAnimations(back); await InvokeAsync(() => { _indicatorsRef?.Refresh(Children.Count, _active); }); ResetTransitionTimer(Children[_active].Interval); }
static App() { HeartBeatTimer = new Timer(10 * 1000); //HeartBeatTimer.SynchronizingObject = null; HeartBeatTimer.Elapsed += delegate { if (Server != null) { try { Server.GetVersion(); HeartBeatTimer.Start(); } catch { try { Server.Abort(); } catch { } Server = null; HeartBeatTimer.Stop(); MessageBox.Show("Disconnected from the server", "Error", MessageBoxButton.OK, MessageBoxImage.Error); Environment.Exit(1); } } else { HeartBeatTimer.Stop(); } }; HeartBeatTimer.AutoReset = false; }
public void DoSend(string locationSemantic, IEnvelope message, int timeout) { var timer = new Timer(timeout * 1000); m_location = locationSemantic; try { _is_completed = false; timer.Elapsed += Timer_Elasped; timer.Start(); this.DoSend(locationSemantic, message); _is_completed = true; timer.Stop(); } catch (Exception exception) { timer.Stop(); throw; } finally { if (timer.Enabled) timer.Stop(); timer.Elapsed -= Timer_Elasped; timer.Dispose(); } }
public override void ViewDidLoad () { base.ViewDidLoad (); // Perform any additional setup after loading the view, typically from a nib. searchField.Text = string.Empty; var keyStrokeTimer = new Timer (500); var timeElapsedSinceChanged = true; keyStrokeTimer.Start (); keyStrokeTimer.Elapsed += (sender, e) => { timeElapsedSinceChanged = true; }; var searchText = ""; searchField.EditingChanged += async (sender, e) => { keyStrokeTimer.Stop (); if (timeElapsedSinceChanged) { // Probably should do some locking timeElapsedSinceChanged = false; keyStrokeTimer.Stop (); if (!string.IsNullOrEmpty (searchField.Text)) { if (!searchText.Equals (searchField.Text)) { searchText = searchField.Text; var results = await SearchCheeses (searchText); foreach (var cheeseName in results) { Console.WriteLine ($"Cheese name: {cheeseName}"); } } } } keyStrokeTimer.Start(); }; // var editing = searchField.Events ().EditingChanged; // // var searchSteam = editing // .Select (_ => searchField.Text) // .Where (t => !string.IsNullOrEmpty (t)) // .DistinctUntilChanged () // .Throttle (TimeSpan.FromSeconds (0.5)) // .SelectMany (t => // SearchCheeses (t)); // // searchSteam.Subscribe ( // r => // r.ForEach(cheeseName => // Console.WriteLine($"Cheese name: {cheeseName}")) // ); }
public PackageDownloader(PlasmaDownloader plasmaDownloader) { this.plasmaDownloader = plasmaDownloader; LoadRepositories(); refreshTimer = new Timer(); refreshTimer.Stop(); refreshTimer.AutoReset = true; refreshTimer.Elapsed += RefreshTimerElapsed; refreshTimer.Stop(); }
private void CloseShadows() { _restoreAnimationTimer?.Stop(); _restoreAnimationTimer?.Dispose(); foreach (var shadowBorder in _shadows) { shadowBorder.Close(); shadowBorder.Dispose(); } _shadows.Clear(); }
//--------------------------------------------------------------------------- /// <summary> /// Конструктор /// </summary> public ComPort() { _SyncRoot = new Object(); _СurrentTransaction = new Modbus.OSIModel.Transaction.Transaction(TransactionType.Undefined, null); _TimerInterFrameDelay = new Timer(20); _TimerInterFrameDelay.AutoReset = false; _TimerInterFrameDelay.Elapsed += new ElapsedEventHandler(EventHandler_TmrInterFrameDelay_Elapsed); _TimerInterFrameDelay.Stop(); _TimerTimeoutCurrentTransaction = new Timer(); _TimerTimeoutCurrentTransaction.AutoReset = false; _TimerTimeoutCurrentTransaction.Interval = 200; _TimerTimeoutCurrentTransaction.Elapsed += new ElapsedEventHandler(EventHandler_TimerTimeoutCurrentTransaction_Elapsed); _TimerTimeoutCurrentTransaction.Stop(); // Настраиваем последовательный порт _SerialPort = new System.IO.Ports.SerialPort("COM1", 19200, Parity.Even, 8, StopBits.One); _SerialPort.ErrorReceived += new SerialErrorReceivedEventHandler(EventHandler_SerialPort_ErrorReceived); _SerialPort.DataReceived += new SerialDataReceivedEventHandler(EventHandler_SerialPort_DataReceived); _SerialPort.ReceivedBytesThreshold = 1; }
public virtual void Stop(MinerStopType willswitch = MinerStopType.SWITCH) { _cooldownCheckTimer?.Stop(); _Stop(willswitch); PreviousTotalMH = 0.0; IsRunning = false; }
private void OnTrackingToggleClick(object sender, RoutedEventArgs e) { if (!(sender is ToggleButton toggleButton)) { return; } var startTracking = toggleButton.IsChecked ?? false; _frequencySlider.IsEnabled = !startTracking; if (startTracking) { GetEvents(); _timer = new Timer(_frequencySlider.Value * 1000); _timer.Elapsed += Timer_Elapsed; _timer.Start(); } else { _timer?.Stop(); _timer?.Dispose(); _timer = null; } }
/// <summary> /// Ends the watch on the log directory /// </summary> public void EndWatch() { //stop the file monitors if (_timerFileChecker != null && _timerFileChecker.Enabled) { _timerFileChecker?.Stop(); } if (_fsw != null) { _fsw.EnableRaisingEvents = false; _fsw?.Dispose(); _fsw = null; } //end all monitors var lstRemove = new List <string>(); foreach (var mon in _dicMonitors) { lstRemove.Add(mon.Key); } foreach (var monKey in lstRemove) { AuctionMonitor monOut; if (_dicMonitors.TryRemove(monKey, out monOut)) { this.OnAuctionMonitorEnded(monOut); } } _watching = false; }
/// <summary> /// Stop the scan and notify the caller that it has ended /// </summary> private void StopScan() { Log("Stop BLE scan"); BluetoothLeScannerCompat scanner = BluetoothLeScannerCompat.Scanner; if (_scanning && scanner != null && _skfScanCallback != null) { // Hold onto this scan callback so we can flush it before any following scan _previousScanCallback = _skfScanCallback; scanner.StopScan(_skfScanCallback); _scanTimer?.Stop(); _scanning = false; // Invoke the caller's callback so they know the scan finished DiscoveryFinished?.Invoke(this, new EventArgs()); } // Clear the event handlers if (_skfScanCallback != null) { Log(string.Format("StopScan: {0} callbacks cleared", _skfScanCallback.ClearCallers())); // _skfScanCallback.Dispose(); _skfScanCallback = null; } //_scanTimer?.Dispose(); _scanTimer = null; }
public Task StopAsync(CancellationToken cancellationToken) { _logger.LogInformation("SermonHosedService is stopping."); _timer?.Stop(); return(Task.CompletedTask); }
protected override void StartService() { try { //create and fire off a timer //simply start our timer -- which will automatically kick off synchronizing //if (_taskPoolManager != null) // _taskPoolManager.ProgressChanged -= synchronizer_ProgressChanged; //_taskPoolManager.ProgressChanged += synchronizer_ProgressChanged; _pollTimer = new System.Timers.Timer() { Enabled = true, Interval = _config.Interval.TotalMilliseconds }; _pollTimer.Elapsed += pollTimer_Elapsed; _pollTimer.Start(); } catch (Exception ex) { _log.FatalException(String.Format("Service {0} - Unexpected Error - Failed to start", ServiceName), ex); if (null != _pollTimer) _pollTimer.Stop(); if (null != _taskPoolManager) { try { _taskPoolManager.CancelAll(); } catch (Exception) { }; } //make sure that Windows knows that we're not running -- with the service messed, we can't throw; } }
void scanSkeys () { if (aTimer == null) try { //TODO fazer animacao para findBleButton..... if (findBleButton != null) findBleButton.Text = "Procurando SafetyKeys"; int scanTime = 15000; aTimer = new Timer (); aTimer.Elapsed += aTimer_Elapsed; aTimer.Interval = scanTime; aTimer.Enabled = true; if (!selMeuSkey) { ((App)Application.Current).mysafetyDll.cancelScan (); if (App.gateSkeys != null) App.gateSkeys.Clear (); devices.Clear (); } IsBusy = true; ((App)Application.Current).mysafetyDll.scanBleDevice (scanTime); } catch (Exception ex) { if (findBleButton != null) findBleButton.Text = "Procurar SafetyKeys"; IsBusy = false; aTimer.Stop (); aTimer = null; Console.WriteLine ("Erro na busca por Skeys:\n\r" + ex.Message); DependencyService.Get<IToastNotificator> ().Notify (ToastNotificationType.Error, "MySafety", "Erro na busca por Skeys:\n\r" + ex.Message, TimeSpan.FromSeconds (3)); IsBusy = false; } }
public void Disconnect() { lock (DisconnectLock) { if (ConnectionState == ConnectionStates.Disconnected) { return; } _ackTimer?.Stop(); _sendTimer?.Stop(); ConnectionState = ConnectionStates.Disconnected; Debug.WriteLine($"Disconnect() ConnectionState={ConnectionState}"); _client?.Close(); Local = false; Logging.Instance.Log(LogTypes.Info, TAG, nameof(Disconnect), $"connection dropped"); Dropped?.Invoke(); Update?.Invoke(); if (CentralexState == CentralexStates.CentralexConnected) { _centralexReconnectTimer.Interval = 5000; _centralexReconnectTimer.Start(); } } }
private void StopIntervalTimer() { //Debug.WriteLine("stop interval timer..."); intervalTimer?.Stop(); intervalTimer?.Dispose(); intervalTimer = null; }
private void OnStopping() { this.logger.LogInformation("OnStopping method called."); int seconds = 0; while (!processCompleted) { Thread.Sleep(1000); seconds++; if (stopServiceTimeout > 0 && (seconds * 1000) > stopServiceTimeout) { break; } } try { _timer?.Stop(); _timer?.Close(); _timer?.Dispose(); } catch (Exception ex) { this.logger.LogError(ex, ex.Message); } }
private void Timer_Elapsed(object sender, ElapsedEventArgs e) { _timer?.Stop(); ExplorerMonitor.Check(); MaximizedMonitor.Check(); _timer?.Start(); }
public ErrorHighlighter(IWpfTextView view, ITextDocument document, IVsTaskList tasks, DTE2 dte) { _view = view; _document = document; _text = new Adornment(); _tasks = tasks; _dispatcher = Dispatcher.CurrentDispatcher; _adornmentLayer = view.GetAdornmentLayer(ErrorHighlighterFactory.LayerName); _view.ViewportHeightChanged += SetAdornmentLocation; _view.ViewportWidthChanged += SetAdornmentLocation; _text.MouseUp += (s, e) => { dte.ExecuteCommand("View.ErrorList"); }; _timer = new Timer(750); _timer.Elapsed += (s, e) => { _timer.Stop(); Task.Run(() => { _dispatcher.Invoke(new Action(() => { Update(false); }), DispatcherPriority.ApplicationIdle, null); }); }; _timer.Start(); }
// GET: RunSystemAdministrator public ActionResult RunSystemAdministrator() { IWebDriver driver = new FirefoxDriver(); driver.Navigate().GoToUrl("http://localhost:4601/"); var emp = _employeeService .Queryable() .Where(x => x.DepartmentRoleId == 9) .FirstOrDefault(); emp.EmployeeLogin = _employeeLoginService .Queryable() .Where(x => x.EmployeeId == emp.EmployeeId) .FirstOrDefault(); IWebElement UserName = driver.FindElement(By.Name("UserName")); IWebElement Password = driver.FindElement(By.Name("Password")); var loginButton = driver.FindElement(By.XPath("/html/body/div/div/div/section/form/button")); UserName.SendKeys(emp.EmployeeLogin.UserName); Password.SendKeys(emp.EmployeeLogin.Password); loginButton.Click(); Timer timer = new Timer(1000); timer.Start(); timer.Stop(); return View(); }
public static void Main(string[] args) { Console.Write("Loading current event status . . . "); m_EventStatus = new EventTimerRequest().Execute().Events.ToDictionary(ev => ev.Id); m_Data = new List<EventSpawnData>(); Console.WriteLine("Done."); // start the timer m_TimerSync = 0; m_Timer = new Timer(m_PollRate.TotalMilliseconds); m_Timer.Elapsed += WorkerThread; m_Timer.Start(); Console.WriteLine("Beginning window analysis. Press any key to cease gathering data."); Console.ReadKey(); Console.WriteLine(); Console.Write("Halting window analysis . . . "); // stop timer m_Timer.Stop(); // wait for any existing threads to complete SpinWait.SpinUntil(() => Interlocked.CompareExchange(ref m_TimerSync, -1, 0) == 0); Console.WriteLine("Done."); Console.Write("Writing data to file [data.csv] . . . "); StreamWriter sw = new StreamWriter("data.csv"); sw.WriteLine("ev_id, spawn_time, failed"); foreach (EventSpawnData data in m_Data) sw.WriteLine("{0}, {1}, {2}", data.ev_id, data.spawn_time.ToString("G"), data.failed); sw.Close(); }
public Task StopAsync(CancellationToken cancellationToken) { mLogger.LogDebug("Stopping timer"); mTriangleNotifierTimer?.Stop(); return(Task.CompletedTask); }
public void Unregister() { NotificationTimer?.Stop(); MessagenTimer?.Stop(); NotificationTimer = null; MessagenTimer = null; }
private void OnTimedEvent(Object source, ElapsedEventArgs e) { Device.BeginInvokeOnMainThread(() => { if (timerBegin != expireTime) { DateTime dateTime = DateTime.Now; TimeSpan _TimeSpan = TimeSpan.FromSeconds(expireTime - timerBegin); TimerValue.Text = (expireTime - timerBegin).ToString(); string seconds = "00"; if (_TimeSpan.Seconds < 10) { seconds = Terra.Core.Utils.Utils.pad_an_int(_TimeSpan.Seconds, 2); } else { seconds = _TimeSpan.Seconds.ToString(); } timerBegin = timerBegin + 1; } else { timer?.Stop(); isTimerStarted = false; } }); }
/// <summary> /// /// </summary> /// <param name="Action"></param> public static void InfiniteLoopDetector(Action Action) { using (var Timer = new Timer(4.0 * 1000)) { bool Cancel = false; Timer.Elapsed += (sender, e) => { if (!Cancel) { Console.WriteLine("InfiniteLoop Detected! : {0}", e.SignalTime); } }; Timer.AutoReset = false; Timer.Start(); try { Action(); } finally { Cancel = true; Timer.Enabled = false; Timer.Stop(); } } }
protected override void InitializeImpl() { this._timers = this.TimerJobs .Where(j => j.Item1 > 0.0) .OrderBy(j => j.Item1) .Select(j => { Timer timer = new Timer(j.Item1); timer.Elapsed += (sender, e) => { timer.Stop(); try { this.Host.RequestManager.Execute<Object>(Request.Parse(j.Item2)); } finally { timer.Start(); } }; return timer; }).ToList(); this.RunInitializingJobs(); base.InitializeImpl(); }
// Initialize the email server public void Init() { try { logger.Info("Initialize in progress...."); // Priority emails send every thirty seconds and normal emails send every ten minutes _normalEmails = new Timer(Int32.Parse(ConfigurationManager.AppSettings["NormalEmailSendTimerTick"])); _priorityEmails = new Timer(Int32.Parse(ConfigurationManager.AppSettings["ImportantEmailSendTimerTick"])); LoadLayouts(); // Start new threads to send the normal and important emails. _normalEmails.Elapsed += (sender, args) => { _normalEmails.Stop(); Task<bool>.Factory.StartNew(ExecuteNormalEmails); _normalEmails.Start(); }; _priorityEmails.Elapsed += (sender, args) => { _priorityEmails.Stop(); Task<bool>.Factory.StartNew(ExecuteImportantEmails); _priorityEmails.Start(); }; logger.Info("Initialize finished."); } catch (Exception e) { logger.Error("Loading layouts", e); ErrorDatabaseManager.AddException(e, typeof(EmailServer), additionalInformation: "RDN Email Server Service failure, Load layouts failed"); } }
public RoslynCodeAnalysisHelper(IWpfTextView view, ITextDocument document, IVsTaskList tasks, DTE2 dte, SVsServiceProvider serviceProvider, IVsActivityLog log) { _view = view; _document = document; _text = new Adornment(); _tasks = tasks; _serviceProvider = serviceProvider; _log = log; _dispatcher = Dispatcher.CurrentDispatcher; _adornmentLayer = view.GetAdornmentLayer(RoslynCodeAnalysisFactory.LayerName); _view.ViewportHeightChanged += SetAdornmentLocation; _view.ViewportWidthChanged += SetAdornmentLocation; _text.MouseUp += (s, e) => dte.ExecuteCommand("View.ErrorList"); _timer = new Timer(750); _timer.Elapsed += (s, e) => { _timer.Stop(); System.Threading.Tasks.Task.Run(() => { _dispatcher.Invoke(new Action(() => Update(false)), DispatcherPriority.ApplicationIdle, null); }); }; _timer.Start(); }
public void TestTimerStartAutoReset() { CountdownEvent cde = new CountdownEvent(1); int result = 0; _timer = new TestTimer(1); // Test defaults. Assert.Equal(1, _timer.Interval); Assert.True(_timer.AutoReset); _timer.AutoReset = false; _timer.Elapsed += (sender, e) => { result = ++result; cde.Signal(); }; _timer.Start(); Assert.True(_timer.Enabled); cde.Wait(); // Only elapsed once. Assert.Equal(1, result); cde = new CountdownEvent(10); _timer.AutoReset = true; cde.Wait(); cde.Dispose(); _timer.Stop(); // Atleast elapsed 10 times. Assert.True(result >= 10); }
protected override void InitializeImpl() { this._timers = this.Configuration.ResolveValue<List<Struct<Double, String>>>("timerJobs") .Where(j => j.Item1 > 0.0) .OrderBy(j => j.Item1) .Select(j => { Timer timer = new Timer(j.Item1); timer.Elapsed += (sender, e) => { timer.Stop(); try { this.Host.RequestManager.Execute<Object>(Request.Parse(j.Item2)); } // Provision for problems of remote services catch (WebException) { } timer.Start(); }; return timer; }).ToList(); this.RunInitializingJobs(); base.InitializeImpl(); }
static void Main(string[] args) { GenericPrincipal principal = new GenericPrincipal(new GenericIdentity("Miguel"), new string[] { "CarRentalAdmin" }); Thread.CurrentPrincipal = principal; ObjectBase.Container = MEFLoader.Init(); Console.WriteLine("Starting up services"); Console.WriteLine(""); SM.ServiceHost hostInventoryManager = new SM.ServiceHost(typeof(InventoryManager)); SM.ServiceHost hostRentalManager = new SM.ServiceHost(typeof(RentalManager)); SM.ServiceHost hostAccountManager = new SM.ServiceHost(typeof(AccountManager)); StartService(hostInventoryManager, "InventoryManager"); StartService(hostRentalManager, "RentalManager"); StartService(hostAccountManager, "AccountManager"); System.Timers.Timer timer = new Timer(10000); timer.Elapsed += OnTimerElapsed; timer.Start(); Console.WriteLine(""); Console.WriteLine("Press [Enter] to exit."); Console.ReadLine(); timer.Stop(); Console.WriteLine("Reservation Monitor Stopped"); StopService(hostInventoryManager, "InventoryManager"); StopService(hostRentalManager, "RentalManager"); StopService(hostAccountManager, "AccountManager"); }
public void TestTimerStartAutoReset() { using (var timer = new TestTimer(1)) { var mres = new ManualResetEventSlim(); int count = 0; int target = 1; timer.AutoReset = false; timer.Elapsed += (sender, e) => { if (Interlocked.Increment(ref count) == target) { mres.Set(); } }; timer.Start(); mres.Wait(); Assert.False(timer.Enabled, "Auto-reset timer should not be enabled after elapsed"); Assert.Equal(1, count); count = 0; target = 10; mres.Reset(); timer.AutoReset = true; mres.Wait(); timer.Stop(); Assert.InRange(count, target, int.MaxValue); } }
private void MainWindow_FormClosing(object sender, FormClosingEventArgs e) { // No idea which of these are triggering on rare occasions, perhaps Deactivate, sizechanged or filterWindow. FormClosing -= MainWindow_FormClosing; SizeChanged -= OnMinimizeWindow; _stashManager?.Dispose(); _stashManager = null; _backupBackgroundTask?.Dispose(); _timerReportUsage?.Stop(); _timerReportUsage?.Dispose(); _timerReportUsage = null; _tooltipHelper?.Dispose(); _buddyBackgroundThread?.Dispose(); _buddyBackgroundThread = null; _itemSynchronizer?.Dispose(); _itemSynchronizer = null; panelHelp.Controls.Clear(); _injector?.Dispose(); _injector = null; _window?.Dispose(); _window = null; IterAndCloseForms(Controls); }
static void Main(string[] args) { Timer checkWindows = new System.Timers.Timer(2000); checkWindows.Elapsed += new ElapsedEventHandler(OnTimedEvent); checkWindows.Enabled = true; Console.ReadLine(); checkWindows.Stop(); }
public void Stop() { lock (_lock) { _timer?.Stop(); _timer?.Dispose(); _timer = null; } }
public Task StopAsync(CancellationToken cancellationToken) { Console.WriteLine("MessageProducer service is stopping."); _timer?.Stop(); Console.WriteLine("MessageProducer service is stopped."); return(Task.CompletedTask); }
public Heart(ConnectionMonitor connection, Configuration.EngineSection config) { if (config.Scheduler.Interval < 1) throw new ArgumentException("Cannot beat at a pace below 1 per second. Set engine.scheduler.interval to at least 1.", "config"); timer = new Timer(config.Scheduler.Interval * 1000); timer.Elapsed += new ElapsedEventHandler(timer_Elapsed); connection.Online += delegate { timer.Start(); }; connection.Offline += delegate { timer.Stop(); }; }
private CommitNotifier() { _t = new Timer(3000); _t.Elapsed += (s, e) => { _t.Stop(); Dispatcher.Invoke(() => IsCommit = false); }; }
public MusicPanel(PanelManager man) { manager = man; clearColor = new ColorManager(); clearColor.Color = new Color(255,255,255); timer = new Timer(1000d / 30d); timer.Stop(); timer.Elapsed += new ElapsedEventHandler(timer_Elapsed); }
public MainStationViewModel( ILoadingIndicatorService loadingIndicatorService, IRadio radio, IToastService toastService, ILoggerFacade logger, IDocumentStore documentStore) { _loadingIndicatorService = loadingIndicatorService; _radio = radio; _toastService = toastService; _logger = logger; _documentStore = documentStore; _fetchPreviewTimer = new Timer(1000); _fetchPreviewTimer.Elapsed += FetchPreviewTimerTick; _scheduler = TaskScheduler.FromCurrentSynchronizationContext(); _styles = new ObservableCollection<TermModel>(); _moods = new ObservableCollection<TermModel>(); _selectedMoods = new ObservableCollection<TermModel>(); _selectedMoods.CollectionChanged += (sender, args) => { RaisePropertyChanged("SelectedMoodsText"); _fetchPreviewTimer.Stop(); _fetchPreviewTimer.Start(); }; _selectedStyles = new ObservableCollection<TermModel>(); _selectedStyles.CollectionChanged += (sender, args) => { RaisePropertyChanged("SelectedStylesText"); _fetchPreviewTimer.Stop(); _fetchPreviewTimer.Start(); }; ToggleStyleCommand = new StaticCommand<TermModel>(ExecuteToggleStyle); ToggleMoodCommand = new StaticCommand<TermModel>(ExecuteToggleMood); StartRadioCommand = new AutomaticCommand(ExecuteStartRadio, CanExecuteStartRadio); IncreaseBoostCommand = new StaticCommand<TermModel>(ExecuteIncreaseBoost); DecreaseBoostCommand = new StaticCommand<TermModel>(ExecuteDecreaseBoost); RequireTermCommand = new StaticCommand<TermModel>(ExecuteRequireTerm); BanTermCommand = new StaticCommand<TermModel>(ExecuteBanTerm); Tempo = new Range(); Tempo.Rounding = MidpointRounding.ToEven; Tempo.RangeChanged += MetricChanged; Loudness = new Range(); Loudness.RangeChanged += MetricChanged; Energy = new Range(); Energy.RangeChanged += MetricChanged; ArtistFamiliarity = new Range(); ArtistFamiliarity.RangeChanged += MetricChanged; ArtistHotness = new Range(); ArtistHotness.RangeChanged += MetricChanged; SongHotness = new Range(); SongHotness.RangeChanged += MetricChanged; Danceability = new Range(); Danceability.RangeChanged += MetricChanged; }
public static void Schedule(PythonFunction func, double Time) { Timer timer = new Timer(); timer.Interval = Time * 1000; timer.Elapsed += delegate(object sender, ElapsedEventArgs args){ timer.Stop(); ResourceManager.Engine.Operations.Invoke(func); }; timer.Start(); }
public Task StopAsync(CancellationToken stopToken) { logger.LogInformation("Stopping input monitoring"); timer?.Stop(); logger.LogInformation("Input monitoring stopped"); return(Task.CompletedTask); }
static void TimersTimer() { System.Timers.Timer t1 = new System.Timers.Timer(1000); t1.AutoReset = true; t1.Elapsed += TimeAction; t1.Start(); Thread.Sleep(10000); t1.Stop(); t1.Dispose(); }
public Worker(Logger Log) { _log = Log; _proxyList = new ProxyList(_log); _timer = new Timer(); _timer.Elapsed += ElapsedEvent; _timer.Stop(); }
private static void F1() { /*Timer t = new Timer(new TimerCallback(func)); t.Change(0, 1000); //Thread.Sleep(4000); Console.WriteLine("hi"); Console.ReadKey(); */ Timer t = new Timer(); t.Interval = 10; t.Elapsed += new ElapsedEventHandler(Event); t.Start(); Console.ReadKey(); t.Stop(); t.Start(); Console.ReadKey(); t.Stop(); }
public void Track() { _DelayedTrack = new Timer(30*1000 /*30 sec delay*/) { AutoReset = true, Enabled = true}; _DelayedTrack.Elapsed += (o, e) => { try { if (_Tries > 10) { _DelayedTrack.Stop(); } TrackUsageInternal(); _DelayedTrack.Stop(); _DelayedTrack.Dispose(); } catch (Exception exc) { _Logger.WarnException("Failed to track usage", exc); _Tries++; } }; }
public void BiometricsLogin() { var context = new LAContext(); NSError AuthError; var myReason = new NSString(LoginScreenData.BioLoginMessage); if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out AuthError)) { var replyHandler = new LAContextReplyHandler((success, error) => { this.InvokeOnMainThread(() => { if (success) { var obj = Global.DatabaseManager.GetUsername(); var pwd = Encrypt.DecryptString(obj.PWD); Dictionary<string, string> parameters = new Dictionary<string, string>(); parameters.Add("username", obj.Username); parameters.Add("password", pwd); parameters.Add("app_device_number", Device.DeviceID); loginScreenView.Hide(); initLoadingScreenView(LoginScreenData.LoadingScreenTextLogin); atimer = new Timer(1000); atimer.Elapsed += (s, e) => { if (ServerURLReady) { InvokeOnMainThread(() => { LoginWebCall(parameters); atimer.Stop(); atimer.Dispose(); }); } }; atimer.AutoReset = true; atimer.Enabled = true; } else if (error!=null && error.ToString().Contains("Application retry limit exceeded")){ //Show fallback mechanism here new UIAlertView(LoginScreenData.AlertScreenBioLoginFailTitle, error.ToString()+" "+LoginScreenData.AlertScreenBioLoginFaildMessage, null, LoginScreenData.AlertScreenBioLoginFaildCancelBtnTitle, null).Show(); } PWDLogin(); }); }); context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, myReason, replyHandler); } else { loginScreenView.userNameTextField.Hidden = false; loginScreenView.passwordTextField.Hidden = false; loginScreenView.loginBtn.Hidden = false; loginScreenView.fingerPrintView.Hidden = true; } }
// Drone constructor public Drone(string droneId, DroneType droneType, int maxSpeed, double airborneAltitudeSet) { this.Droneid = droneId; this.Type = droneType; this.maxSpeedLimit = maxSpeed; this.airborneAltitude = airborneAltitudeSet; this.flightTimer = new Timer(1000); flightTimer.Stop(); // add event handler for timer tick of flight control flightTimer.Elapsed += FlightTimer_Elapsed; }
/// <summary> /// Update the text contents of the file /// </summary> public void UpdateSourceFile(Uri fileUri, TextChangedEvent textChangedEvent) { FileCompiler fileCompilerToUpdate = null; if (OpenedFileCompiler.TryGetValue(fileUri, out fileCompilerToUpdate)) { _semanticUpdaterTimer?.Stop(); fileCompilerToUpdate.CompilationResultsForProgram.UpdateTextLines(textChangedEvent); if (IsLsrSourceTesting) { //Log text lines string var sb = new StringBuilder(); foreach (var cobolTextLine in fileCompilerToUpdate.CompilationResultsForProgram.CobolTextLines) { sb.AppendLine(cobolTextLine.SourceText); } _Logger(sb.ToString(), fileUri); } var handler = new Action <object, ExecutionStepEventArgs>((sender, args) => { ExecutionStepEventHandler(sender, args, fileUri); }); //Subscribe to FileCompilerEvent fileCompilerToUpdate.ExecutionStepEventHandler += handler.Invoke; var execStep = LsrTestOptions.ExecutionStep(fileCompilerToUpdate.CompilerOptions.ExecToStep); if (execStep > ExecutionStep.SyntaxCheck) { execStep = ExecutionStep.SyntaxCheck; //The maximum execstep authorize for incremental parsing is SyntaxCheck, } //further it's for semantic, which is handle by NodeRefresh method fileCompilerToUpdate.CompileOnce(execStep, fileCompilerToUpdate.CompilerOptions.HaltOnMissingCopy, fileCompilerToUpdate.CompilerOptions.UseAntlrProgramParsing); fileCompilerToUpdate.ExecutionStepEventHandler -= handler.Invoke; if (LsrTestOptions == LsrTestingOptions.NoLsrTesting || LsrTestOptions == LsrTestingOptions.LsrSemanticPhaseTesting) { if (!_timerDisabled) //If TimerDisabled is false, create a timer to automatically launch Node phase { lock (_fileCompilerWaittingForNodePhase) { if (!_fileCompilerWaittingForNodePhase.Contains(fileCompilerToUpdate)) { _fileCompilerWaittingForNodePhase.Add(fileCompilerToUpdate); //Store that this fileCompiler will soon need a Node Phase } } _semanticUpdaterTimer = new System.Timers.Timer(750); _semanticUpdaterTimer.Elapsed += (sender, e) => TimerEvent(sender, e, fileCompilerToUpdate); _semanticUpdaterTimer.Start(); } } } }
private void ExecuteWarpper(object source, ElapsedEventArgs args) { if (args.SignalTime.ToString("yyyy-MM-dd HH:mm:ss") == this.txtSetTime.Text) { Timer timer = source as Timer; timer?.Stop(); MethodInvoker mi = new MethodInvoker(this.BatchUpload); this.BeginInvoke(mi); } }
protected override async void OnPause() { base.OnPause(); _timer?.Stop(); _pauseTime = DateTime.Now; if (_hasWearAPIs) { await WearableClass.GetCapabilityClient(this).RemoveListenerAsync(this, WearRefreshCapability); } }
public void Disconnect() { if (Connected) { _controlWriter.WriteLine("QUIT"); _controlReader.Close(); _controlWriter.Close(); _controlConnection.Close(); _timer?.Stop(); Connected = false; } }
public void CloseConnection() { lock (_lockObject) { _clientSocket?.Close(); _clientSocket?.Dispose(); _udpClient?.Close(); _udpClient?.Dispose(); _timeoutTimer?.Stop(); } }
public void Refresh() { if (timer == null) { return; } timer?.Stop(); if (Duration != 0) { timer?.Start(); } NotifyPropertyChanged("Refresh"); }
private void MoveNeedle(object sender, ElapsedEventArgs e) { if (control?.Controls.ContainsKey("Needle") == true) { var needle = control.Controls["Needle"]; UpdateNeedle(control.Controls["Needle"]); } else { animateTimer?.Stop(); animateTimer?.Dispose(); animateTimer = null; } }
public async Task ConnectAsync() { timer?.Stop(); AuthConfiguration = new LogDNAAuthenticationRequest { Tags = string.Join(",", Configuration.Tags), HostName = Configuration.HostName }; HttpStatusCode status = HttpStatusCode.Unused; int tries = 0; while (status != HttpStatusCode.OK && tries < 10) { using (var request = new HttpRequestMessage(HttpMethod.Post, $"https://{AuthResult?.ApiServer ?? DefaultLogDNAHost}/authenticate/{Configuration.IngestionKey}")) { request.Headers.Add("User-Agent", $"{AuthConfiguration.AgentName}/{AuthConfiguration.AgentVersion}"); request.Content = new StringContent(JsonConvert.SerializeObject(AuthConfiguration, authJsonSettings), Encoding.UTF8, "application/json"); HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false); response.EnsureSuccessStatusCode(); AuthResult = JsonConvert.DeserializeObject <LogDNAAuthenticationResponse>(await response.Content.ReadAsStringAsync().ConfigureAwait(false)); status = response.StatusCode; if (status != HttpStatusCode.OK) { InternalLogger("Auth failed; Connection will be retried after a delay."); Thread.Sleep(Configuration.AuthFailDelay); tries++; } if (status == HttpStatusCode.OK && !string.IsNullOrWhiteSpace(AuthResult?.ApiServer) && !AuthResult.ApiServer.Equals(DefaultLogDNAHost, StringComparison.OrdinalIgnoreCase) && AuthResult.Ssl) { status = HttpStatusCode.Unused; } else { AuthResult.ApiServer ??= DefaultLogDNAHost; } } } if (status == HttpStatusCode.OK) { Connected = true; timer.Start(); } }
public void StopRecording() { /*Stop the timer*/ _timer?.Stop(); /*Destroy/Dispose of the timer to free memory*/ _timer?.Dispose(); /*Stop the audio recording*/ if (_waveSource != null) { _waveSource.StopRecording(); } }