public Task StartAsync(CancellationToken cancellationToken) { _logger.LogInformation("RQUEST Polling Service started."); _timer = new Timer(PollRquest); RunTimerOnce(); return(Task.CompletedTask); }
private (bool diagnosticSourceEnabled, Activity?activity) InitializeCall(HttpRequestMessage request, TimeSpan?timeout) { GrpcCallLog.StartingCall(Logger, Method.Type, request.RequestUri); GrpcEventSource.Log.CallStart(Method.FullName); // Deadline will cancel the call CTS. // Only exceed deadline/start timer after reader/writer have been created, otherwise deadline will cancel // the call CTS before they are created and leave them in a non-canceled state. if (timeout != null && !Channel.DisableClientDeadline) { if (timeout.Value <= TimeSpan.Zero) { // Call was started with a deadline in the past so immediately trigger deadline exceeded. DeadlineExceeded(); } else { GrpcCallLog.StartingDeadlineTimeout(Logger, timeout.Value); var dueTime = GetTimerDueTime(timeout.Value); _deadlineTimer = new Timer(DeadlineExceededCallback, null, dueTime, Timeout.Infinite); } } var diagnosticSourceEnabled = GrpcDiagnostics.DiagnosticListener.IsEnabled() && GrpcDiagnostics.DiagnosticListener.IsEnabled(GrpcDiagnostics.ActivityName, request); Activity?activity = null; // Set activity if: // 1. Diagnostic source is enabled // 2. Logging is enabled // 3. There is an existing activity (to enable activity propagation) if (diagnosticSourceEnabled || Logger.IsEnabled(LogLevel.Critical) || Activity.Current != null) { activity = new Activity(GrpcDiagnostics.ActivityName); activity.AddTag(GrpcDiagnostics.GrpcMethodTagName, Method.FullName); activity.Start(); if (diagnosticSourceEnabled) { GrpcDiagnostics.DiagnosticListener.Write(GrpcDiagnostics.ActivityStartKey, new { Request = request }); } } if (Options.CancellationToken.CanBeCanceled) { // The cancellation token will cancel the call CTS. // This must be registered after the client writer has been created // so that cancellation will always complete the writer. _ctsRegistration = Options.CancellationToken.Register(() => { using (StartScope()) { CancelCall(new Status(StatusCode.Cancelled, "Call canceled by the client.")); } }); } return(diagnosticSourceEnabled, activity); }
private Task _ws_WebsocketClosed(string arg) { if (!string.IsNullOrWhiteSpace(arg)) { Log.Warning("Voice Websocket closed: {Arg}", arg); } var hbt = _heartbeatTimer; hbt?.Change(Timeout.Infinite, Timeout.Infinite); _heartbeatTimer = null; if (!_stopCancellationToken.IsCancellationRequested && shouldResume) { _ = _ws.RunAndBlockAsync(_websocketUrl, _stopCancellationToken); return(Task.CompletedTask); } _ws.WebsocketClosed -= _ws_WebsocketClosed; _ws.PayloadReceived -= _ws_PayloadReceived; if (!_stopCancellationToken.IsCancellationRequested) { _stopCancellationSource.Cancel(); } return(this.OnClosed(this)); }
public async Task <ActionResult <string> > Get() { var graphServiceClient = GetGraphClient(); var sub = new Microsoft.Graph.Subscription(); sub.ChangeType = "updated"; sub.NotificationUrl = config.Ngrok + "/api/notifications"; sub.Resource = "/users"; sub.ExpirationDateTime = DateTime.UtcNow.AddMinutes(15); sub.ClientState = "SecretClientState"; var newSubscription = await graphServiceClient .Subscriptions .Request() .AddAsync(sub); Subscriptions[newSubscription.Id] = newSubscription; if (subscriptionTimer == null) { subscriptionTimer = new Timer(CheckSubscriptions, null, 5000, 15000); } return($"Subscribed. Id: {newSubscription.Id}, Expiration: {newSubscription.ExpirationDateTime}"); }
public Task StartAsync(CancellationToken cancellationToken) { _logger.LogInformation("Start timer."); _timer = new Timer(CheckReminders, null, 0, 60000); return(Task.CompletedTask); }
public void Start() { if (_timer == null) { lock (_lockObj) { if (_disposed) { return; } if (_timer == null) { // This fixes the cycle by using a WeakReference to the state object. The object graph now looks like this: // Timer -> TimerHolder -> TimerQueueTimer -> WeakReference<TimerAwaitable> -> Timer -> ... // If TimerAwaitable falls out of scope, the timer should be released. _timer = NonCapturingTimer.Create(state => { var weakRef = (WeakReference <TimerAwaitable>)state !; if (weakRef.TryGetTarget(out var thisRef)) { thisRef.Tick(); } }, state: new WeakReference <TimerAwaitable>(this), dueTime: _dueTime, period: _period); } } } }
public void Init() { if (_useDepositTimer) { if (_depositTimer == null) { if (_ethJsonRpcClientProxy == null) { if (_logger.IsError) { _logger.Error("Cannot find any configured ETH proxy to run deposit timer."); } return; } _depositTimer = new Timer(_depositTimerPeriod); _depositTimer.Elapsed += DepositTimerOnElapsed; _depositTimer.Start(); } if (_logger.IsInfo) { _logger.Info("Initialized NDM consumer services background processor."); } } else { _blockProcessor.BlockProcessed += OnBlockProcessed; } }
/// <summary> /// Destroy the timer, toolwindow, and the error window itself. /// </summary> private void EnsureDestroyed() { if (_timer is not null) { _timer.Dispose(); _timer = null; } if (_tipWindow is not null) { _tipWindow.DestroyHandle(); _tipWindow = null; } // Hide the window and invalidate the parent to ensure // that we leave no visual artifacts. given that we // have a bizarre region window, this is needed. User32.SetWindowPos( new HandleRef(this, Handle), User32.HWND_TOP, _windowBounds.X, _windowBounds.Y, _windowBounds.Width, _windowBounds.Height, User32.SWP.HIDEWINDOW | User32.SWP.NOSIZE | User32.SWP.NOMOVE); _parent?.Invalidate(true); DestroyHandle(); }
public Task StartAsync(CancellationToken cancellationToken) { _logger.LogInformation("Timed Hosted Service running."); _timer = new Timer(Process, null, TimeSpan.Zero, TimeSpan.FromSeconds(_options.ResendIntervalInSeconds)); return(Task.CompletedTask); }
static public async Task T3_SecondTimerLater() { int wasCalled = 0; Timer?timer1 = null; Timer?timer2 = null; try { _installWrapper.Call(); timer1 = new Timer((_) => { Console.WriteLine("In timer1"); wasCalled++; }, null, 10, 0); timer2 = new Timer((_) => { Console.WriteLine("In timer2"); wasCalled++; }, null, 20, 0); var setCounter = (int)_getRegisterCount.Call(); Assert.True(0 == wasCalled, $"wasCalled: {wasCalled}"); Assert.True(1 == setCounter, $"setCounter: {setCounter}"); } finally { await WaitForCleanup(); Assert.True(2 == wasCalled, $"wasCalled: {wasCalled}"); timer1?.Dispose(); timer2?.Dispose(); } }
private void StartUpgradeTimer() { if (_logger.IsDebug) { _logger.Debug("Starting eth sync peer upgrade timer"); } _upgradeTimer = new Timer(_allocationsUpgradeIntervalInMs); _upgradeTimer.Elapsed += (s, e) => { try { _upgradeTimer.Enabled = false; UpgradeAllocations(); } catch (Exception exception) { if (_logger.IsDebug) { _logger.Error("Allocations upgrade failure", exception); } } finally { _upgradeTimer.Enabled = true; } }; _upgradeTimer.Start(); }
/// <summary> /// Override this method and dispose any objects you own the lifetime of if disposing is true. /// </summary> /// <param name="disposing">True if managed objects should be disposed, if false, only unmanaged resources should be released.</param> private void Dispose(bool disposing) { if (_disposed) { return; } if (disposing) { _disposed = true; _logger.LogDebug("Disposing instance."); _rebroadcastAliveNotificationsTimer?.Dispose(); _rebroadcastAliveNotificationsTimer = null; _networkManager.NetworkChanged -= NetworkChanged; DlnaServerPlugin.Instance !.ConfigurationChanging -= UpdateConfiguration; var tasks = Devices.ToList().Select(RemoveDevice).ToArray(); Task.WaitAll(tasks); // Must be last, or there won't be any sockets available. Server.DeleteEvent("M-SEARCH", RequestReceived); } _disposed = true; }
protected override void OnInitialized() { //refresh ui every 800ms _Timer = new Timer(_ => InvokeAsync(StateHasChanged), null, 800, 800); ConsoleInputEvent += BlazorConsoleComponent_CommandInputEvent; base.OnInitialized(); }
/// <summary> /// Stars waiting for the trigger action. /// </summary> /// <param name="lastResult">The last result.</param> /// <param name="logger">The logger.</param> /// <param name="taskName">The name of the task.</param> /// <param name="isApplicationStartup">if set to <c>true</c> [is application startup].</param> public void Start(TaskResult lastResult, ILogger logger, string taskName, bool isApplicationStartup) { DisposeTimer(); DateTime triggerDate; if (lastResult == null) { // Task has never been completed before triggerDate = DateTime.UtcNow.AddHours(1); } else { triggerDate = new[] { lastResult.EndTimeUtc, _lastStartDate }.Max().Add(_interval); } if (DateTime.UtcNow > triggerDate) { triggerDate = DateTime.UtcNow.AddMinutes(1); } var dueTime = triggerDate - DateTime.UtcNow; var maxDueTime = TimeSpan.FromDays(7); if (dueTime > maxDueTime) { dueTime = maxDueTime; } _timer = new Timer(state => OnTriggered(), null, dueTime, TimeSpan.FromMilliseconds(-1)); }
private void RunUntil(object?state) { StopMotor(PortLeft); StopMotor(PortRight); _timer?.Dispose(); _timer = null; }
/// <inheritdoc cref="IHostedService"/> public Task StartAsync(CancellationToken cancellationToken) { _logger.LogInformation("Trip Logger Service starting"); _timer = new Timer(DoLogging, null, TimeSpan.Zero, TimeSpan.FromMinutes(5)); return(Task.CompletedTask); }
public async Task StartAsync(CancellationToken cancellationToken) { _logger.LogInformation(@"Startup Leader Elector for operator ""{operatorName}"".", _settings.Name); _leaseCheck?.Dispose(); _leaseCheck = new Timer( TimeSpan.FromSeconds(_settings.LeaderElectionCheckInterval).TotalMilliseconds) { AutoReset = true, }; _logger.LogTrace("Fetching namespace for leader election."); _namespace = await _client.GetCurrentNamespace(); _operatorDeployment = (await _client.List <V1Deployment>( _namespace, new EqualsSelector("operator-deployment", _settings.Name))).FirstOrDefault(); if (_operatorDeployment != null) { _operatorDeployment.Kind = V1Deployment.KubeKind; _operatorDeployment.ApiVersion = $"{V1Deployment.KubeGroup}/{V1Deployment.KubeApiVersion}"; } #if DEBUG _election.LeadershipChanged(LeaderState.Leader); #else _leaseCheck.Start(); _leaseCheck.Elapsed += async(_, __) => await CheckLeaderLease(); await CheckLeaderLease(); #endif }
public MainWindow() { InitializeComponent(); titleLead = $"Slapp - {splatTagController.MatchPlayer(null).Length} Players and {splatTagController.MatchTeam(null).Length} Teams loaded! - "; Title = titleLead; // Initialise the delay timer if we have a UI context, otherwise don't use the timer. context = SynchronizationContext.Current; if (context != null) { smoothSearchDelayTimer = new Timer(TimerExpired); } // If we've loaded from a snapshot, then hide the setup button(s). if (sourcesImporter == null) { otherFunctionsGrid.Visibility = Visibility.Collapsed; } // Re-save if needed // SplatTagControllerFactory.SaveDatabase(splatTagController); // Now we've initialised, hook up the check changed. ignoreCaseCheckbox.Checked += CheckedChanged; ignoreCaseCheckbox.Unchecked += CheckedChanged; nearMatchCheckbox.Checked += CheckedChanged; nearMatchCheckbox.Unchecked += CheckedChanged; regexCheckbox.Checked += CheckedChanged; regexCheckbox.Unchecked += CheckedChanged; // Focus the input text box so we can start typing as soon as the program starts. searchInput.Focus(); }
/// <summary> /// Set timer notification of actor /// </summary> /// <param name="dueTime">due time, first event</param> /// <param name="period">every period</param> public void SetTimer(TimeSpan dueTime, TimeSpan period) { _timer.Verify().Assert(x => x == null, "Timer already running"); _timer = new Timer(TimerCallback, null, dueTime, period); ActorManager.Configuration.ActorStartTimerEvent(_workContext.WithMethodName(), ActorKey); }
/// <summary> /// Indicate that the preferences need to be saved to the server /// </summary> /// <remarks> /// Does not save immediately. Sets a timer to save in a few seconds so /// rapid calls only require a single request to the server. /// </remarks> private void SetNeedsPreferencesSave() { this.preferencesSaveTimer?.Stop(); this.preferencesSaveTimer = new Timer(5000); this.preferencesSaveTimer.Elapsed += this.PreferencesSaveTimerElapsed; this.preferencesSaveTimer.Start(); }
public override bool Startup(ApplicationBase app, IConfiguration?config) { Logger?.Info("Starting HTTP Server"); server = new HTTPRPCServer("localhost", 5010); server.Run(); Logger?.Info("Starting Client Sendings by Timer"); var cli = HTTPRPCClient.Client <IHttpAPI>(new Uri("http://localhost:5010/api")); var inprogress = false; timer = new Timer((st) => { if (inprogress) { return; } inprogress = true; try { cnt++; var sw = Stopwatch.StartNew(); var r = cli.Test(cnt); Logger?.Info($"RPC Call Executed in {sw.ElapsedMilliseconds} ms. Result: {r.ToString("HH:mm:ss",CultureInfo.InvariantCulture)}"); } #pragma warning disable CA1031 // Do not catch general exception types catch (Exception ex) { Logger?.Error(ex.Message); } #pragma warning restore CA1031 // Do not catch general exception types inprogress = false; }, null, 5000, 5000); return(true); }
/// <summary> /// Called when the preferences save timer fires /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void PreferencesSaveTimerElapsed(object sender, ElapsedEventArgs e) { this.preferencesSaveTimer?.Stop(); this.preferencesSaveTimer = null; // OBSERVATION: we do not check to see if the save to disk or server was successful _ = await this.SavePreferencesAsync(); }
protected override async Task ExecuteAsync(CancellationToken stoppingToken) { _logger.LogInformation($"Import Worker Starting. Import syncing every {_settings.ImportRunFrequencyMinutes} minutes"); // check for work to do every N minutes _timer = new Timer(PerformTasks, null, TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(_settings.ImportRunFrequencyMinutes)); }
protected override async Task ExecuteAsync(CancellationToken stoppingToken) { _logger.LogInformation($"API Worker Starting. Cache syncing every {_settings.MongoDBSettings.CacheSyncFrequencySeconds}s"); // check for work to do every N seconds _timer = new Timer(PerformTasks, null, TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(_settings.MongoDBSettings.CacheSyncFrequencySeconds)); }
private InfluxDBClient(IInfluxDBHttpClient httpClient, string database, string?retentionPolicy, Action <Exception>?errorCallback, int initialBufferSize, int maxBufferSize, CancellationTokenSource cancellationTokenSource, TimeSpan?forceFlushInterval, ArrayPool <byte> arrayPool) { _errorCallback = errorCallback; var path = retentionPolicy == null ? $"write?db={Uri.EscapeDataString(database)}&precision=ms" : $"write?db={Uri.EscapeDataString(database)}&precision=ms&rp={Uri.EscapeDataString(retentionPolicy)}"; _bufferSize = initialBufferSize; _maxBufferSize = maxBufferSize; _arrayPool = arrayPool; _cancellationTokenSource = cancellationTokenSource ?? new CancellationTokenSource(); _memory = _arrayPool.Rent(initialBufferSize); if (forceFlushInterval != null) { _forceFlushInterval = forceFlushInterval.Value; _timer = new Timer(ForceFlush, null, _forceFlushInterval, _forceFlushInterval); } _output = new InfluxDBOutput(httpClient, path); _task = Run(_cancellationTokenSource.Token); }
private void OnLibraryManagerItemAdded(object sender, ItemChangeEventArgs e) { if (!FilterItem(e.Item)) { return; } lock (_libraryChangedSyncLock) { if (_libraryUpdateTimer == null) { _libraryUpdateTimer = new Timer( LibraryUpdateTimerCallback, null, 5000, Timeout.Infinite); } else { _libraryUpdateTimer.Change(5000, Timeout.Infinite); } _itemsAdded.Add(e.Item); } }
internal partial ValueTask Show(Forms.VisualElement visualElement, SnackBarOptions arguments) { var formsAppBar = System.Windows.Application.Current.MainWindow.FindChild <FormsAppBar>("PART_BottomAppBar"); var currentContent = formsAppBar.Content; var snackBar = new SnackBarLayout(arguments); snackBarTimer = new Timer { Interval = (int)arguments.Duration.TotalMilliseconds }; snackBarTimer.Tick += (sender, e) => { formsAppBar.Content = currentContent; snackBarTimer.Stop(); arguments.SetResult(false); }; snackBar.OnSnackBarActionExecuted += () => { formsAppBar.Content = currentContent; snackBarTimer.Stop(); }; snackBarTimer.Start(); var border = new Border { CornerRadius = new CornerRadius(arguments.CornerRadius.Left, arguments.CornerRadius.Top, arguments.CornerRadius.Right, arguments.CornerRadius.Bottom) }; border.Child = snackBar; formsAppBar.Content = border; return(default);
private async void LibraryUpdateTimerCallback(object state) { List <BaseItem> items; lock (_libraryChangedSyncLock) { items = _itemsAdded.ToList(); _itemsAdded.Clear(); _libraryUpdateTimer !.Dispose(); // Shouldn't be null as it just set off this callback _libraryUpdateTimer = null; } items = items.Take(10).ToList(); foreach (var item in items) { var notification = new NotificationRequest { NotificationType = NotificationType.NewLibraryContent.ToString(), Name = string.Format( CultureInfo.InvariantCulture, _localization.GetLocalizedString("ValueHasBeenAddedToLibrary"), GetItemName(item)), Description = item.Overview }; await SendNotification(notification, item).ConfigureAwait(false); } }
private Task HandleHelloAsync(VoiceHello data) { _receivedAck = true; _heartbeatTimer = new Timer(async _ => { await SendHeartbeatAsync(); }, default, data.HeartbeatInterval, data.HeartbeatInterval);
protected override void Dispose(bool disposing) { if (disposing) { LockedAction(() => { if (_saveTimer is not null) { _saveTimer.Dispose(); _saveTimer = null; _fileWatcher.Changed -= _fileWatcher_Changed; _fileWatcher.Renamed -= _fileWatcher_Renamed; _fileWatcher.Created -= _fileWatcher_Created; if (_autoSave) { Save(); } _fileWatcher.Dispose(); } }); } base.Dispose(disposing); }