public async Task StartAsync() { await _lockManager.InitializeAsync().ConfigureAwait(false); if (_timer == null) { _timer = new Timer { AutoReset = true, Interval = TimerIntervalMs }; _timer.Elapsed += TimerElapsed; } //Try and get the lock var lockHandle = await _lockManager.TryLockAsync(_lockId, TimeSpan.FromSeconds(60), CancellationToken.None).ConfigureAwait(false); if (lockHandle != null) { _singletonScope = new SingletonTimerScope(_log, lockHandle, true); _log.Information("Starting Singleton Processor with name {ProcessorName}", _lockId); await _channelReceiver.StartAsync().ConfigureAwait(false); } else { //someone else has locked this instance, start timer to make sure the owner hasn't died _timer.Enabled = true; } }
private async Task AcquireLock(CancellationToken cancellationToken) { //Try and get the lock var lockHandle = await _lockManager.TryLockAsync(_lockId, LockDuration, cancellationToken).ConfigureAwait(false); if (lockHandle != null) { var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); _singletonScope = new SingletonTimerScope(_log, lockHandle, true, LockRefreshInterval, linkedTokenSource); _log.Information("Starting Singleton Processor with name {ProcessorName}", _lockId); await _channelReceiver.StartAsync(linkedTokenSource.Token).ConfigureAwait(false); _lockPollingEnabled = false; #pragma warning disable 4014 Task.Run(() => { linkedTokenSource.Token.WaitHandle.WaitOne(); //Stop signal received, restart the polling if (!cancellationToken.IsCancellationRequested) { _lockPollingEnabled = true; _log.Information("Singleton Processor with name {ProcessorName} lost its lock", _lockId); } }, cancellationToken).ContinueWith(t => linkedTokenSource.Dispose()); #pragma warning restore 4014 } else { //someone else has locked this instance, start timer to make sure the owner hasn't died _lockPollingEnabled = true; } }
public async Task Execute(IJobExecutionContext context) { try { var schedule = typeof(T).FullName; var lockHandle = await _lockManager .TryLockAsync(schedule, TimeSpan.FromSeconds(60), CancellationToken.None).ConfigureAwait(false); if (lockHandle == null) { //someone else has locked this instance, do nothing return; } _logger.Information("Executing schedule {Schedule}", schedule); using (var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(context.CancellationToken)) { using (new SingletonTimerScope(_logger, lockHandle, false, TimeSpan.FromSeconds(19), linkedTokenSource)) using (var scopedDependencyInjection = _dependencyInjection.GetScope()) { var processor = scopedDependencyInjection.GetInstance <IProcessSchedule <T> >(); await processor.ProcessAsync(linkedTokenSource.Token).ConfigureAwait(false); } } } catch (Exception e) { ConsoleWriter.WriteLine($"Error processing schedule {typeof(T)} {e.Message} {e.StackTrace}"); _logger.Error(e, "Error processing schedule {Schedule}", typeof(T)); } }