public void Register(RconModel rconModel) { _rconModel = rconModel; _nLogListener = new NLogListener(); _nLogListener.LogWrite += NLogListenerOnLogWrite; _cancellationTokenSource = new CancellationTokenSource(); _logWriteTimerTask = PeriodicTaskFactory.Start( () => { ProcessQueue(); }, intervalInMilliseconds: _LogWriteFlushTimeMs, delayInMilliseconds: 1000, duration: -1, maxIterations: -1, synchronous: false, cancelToken: _cancellationTokenSource.Token, periodicTaskCreationOptions: TaskCreationOptions.None); //// Repeat every 1 second //_logWriteTimerAction = ignored1 => // { // if (ignored1.IsCompleted) // return; // FlushBuffer(); // //Task.Delay(_LogWriteFlushTimeMs, _cancellationTokenSource.Token).ContinueWith(ignored2 => _logWriteTimerAction(ignored2), _cancellationTokenSource.Token); // _logWriteTimerTask = Task.Delay(_LogWriteFlushTimeMs, _cancellationTokenSource.Token).ContinueWith(_logWriteTimerAction, _cancellationTokenSource.Token); // }; //// Wait 1 sec, then start above repeating task //_logWriteTimerTask = Task.Delay(1000, _cancellationTokenSource.Token).ContinueWith(_logWriteTimerAction, _cancellationTokenSource.Token); }
public static void OnRepositoryCacheConfig(Type dBContext) { Core.Cmn.AppBase.DependencyInjectionFactory.CreateInjectionInstance <ICheckSqlServiceBrockerRepository>().CheckServiceBrokerOnDb(); var repositoryAssemblies = AppDomain.CurrentDomain.GetAssemblies().Where(ass => ass.FullName.ToLower().Contains(".rep")).ToList(); bool isNeedCache; if (Core.Cmn.ConfigHelper.TryGetConfigValue <bool>("IsNeedCache", out isNeedCache) && !isNeedCache) { repositoryAssemblies = repositoryAssemblies.Where(ass => ass.FullName.ToLower().Contains("core.rep")).ToList(); } // Core.Rep must build it's cache at first of all. var coreRepAssembly = repositoryAssemblies.FirstOrDefault(ass => ass.FullName.ToLower().Contains("core.rep")); if (repositoryAssemblies != null) { repositoryAssemblies.Remove(coreRepAssembly); BuildCachesInAssembly(dBContext, coreRepAssembly, true); } repositoryAssemblies.ForEach(ass => BuildCachesInAssembly(dBContext, ass, true)); PeriodicTaskFactory p = new PeriodicTaskFactory((pt) => { CacheConfig.CacheManagementRepository.Delete(); }, new TimeSpan(0, 0, 1200), new TimeSpan(0, 0, 1200)); p.Start(); if (Core.Cmn.ConfigHelper.GetConfigValue <bool>("EnableCacheServerListener") && !IsCacheServerServiceStart) { StartCacheServerService(); } }
private void WriteSequencesPeriodically(MemoryMappedViewAccessor accessor, List <T> sequences) { foreach (var sequence in sequences) { _entityListToWrite.Enqueue(sequence); } if (_stateTimer != null) { _stateTimer.CancelToken = new CancellationToken(true); } _stateTimer = new PeriodicTaskFactory((task) => { lock (sync) { // var isOwnedMutex = LockKeyData.WaitOne(); LockKeyData.WaitOne(); WriteSequences(accessor); // if (isOwnedMutex) LockKeyData.ReleaseMutex(); } }, new TimeSpan(0, 0, 2), new TimeSpan(0, 0, 2)); _stateTimer.Start(); }
protected override void OnStart(string[] args) { _initializationCancelTokenSource = new CancellationTokenSource(); _intitializationCancellationToken = _initializationCancelTokenSource.Token; _initializationTask = Task.Run(() => { //Kick off polling from here that also uses _intitializationCancellationToken, so that when _initializationCancelTokenSource.Cancel() is invoked from OnStop it will start cancellation chain reaction to stop all running activity. You can pass it even into your methods and check _intitializationCancellationToken.IsCancellationRequested and take appropriate actions. //using the Task timer from the other stack overflow post, You could do something like Task perdiodicTask = PeriodicTaskFactory.Start(() => { Console.WriteLine(DateTime.Now); //execute your logic here that has to run periodically }, intervalInMilliseconds: 5000, // fire every 5 seconds... cancelToken: _intitializationCancellationToken); // Using same cancellation token to manage timer cancellation perdiodicTask.ContinueWith(_ => { Console.WriteLine("Finished!"); }).Wait(); }, _intitializationCancellationToken) .ContinueWith(t => { //deal with any task related errors }, TaskContinuationOptions.OnlyOnFaulted); }
private void RecalculateProductionTimer() { _registryGroupState.Round = 0; if (_syncCycleDescriptor != null) { _syncCycleDescriptor.CancellationTokenSource.Cancel(); _syncCycleDescriptor.CancellationRequested = true; } _syncCycleDescriptor = new SyncCycleDescriptor(_synchronizationContext.LastBlockDescriptor); PeriodicTaskFactory.Start(o => { SyncCycleDescriptor syncCycleDescriptor = (SyncCycleDescriptor)o; SortedList <ushort, RegistryRegisterBlock> transactionStateWitnesses = _registryMemPool.DequeueStateWitnessBulk(); SortedList <ushort, RegistryRegisterUtxoConfidential> transactionUtxoWitnesses = _registryMemPool.DequeueUtxoWitnessBulk(); RegistryFullBlock registryFullBlock = ProduceTransactionsFullBlock(transactionStateWitnesses, transactionUtxoWitnesses, syncCycleDescriptor.SynchronizationDescriptor, syncCycleDescriptor.Round); RegistryShortBlock registryShortBlock = ProduceTransactionsShortBlock(registryFullBlock); SendTransactionsBlocks(registryFullBlock, registryShortBlock); syncCycleDescriptor.Round++; if (syncCycleDescriptor.CancellationRequested) { syncCycleDescriptor.CancellationTokenSource.Cancel(); } }, _syncCycleDescriptor, _registrationPeriodMsec * _registryConfiguration.TotalNodes, _registryConfiguration.Position * _registrationPeriodMsec, cancelToken: _syncCycleDescriptor.CancellationTokenSource.Token, periodicTaskCreationOptions: TaskCreationOptions.LongRunning); }
public void Start() { //Delay first execution until expected time has passed _wrappedAdapter.TaskDelay(_interval * 1000).Wait(); var schedulerTask = PeriodicTaskFactory.Start(() => AddSegmentsToQueue(), intervalInMilliseconds: _interval * 1000, cancelToken: _cancelTokenSource.Token); }
public void Start() { ThreadUtils.Delay(firstPushWindow * 1000).ContinueWith((t) => { SendBulkEvents(); PeriodicTaskFactory.Start(() => { SendBulkEvents(); }, interval * 1000, cancellationTokenSource.Token); }); }
public async Task <bool> AnswerQuestionTimer(long questionid) { var userId = _securityContext.User.Id; var counter = 1; Task perdiodicTask = PeriodicTaskFactory.Start(() => { Console.WriteLine($"===========================Begin({counter})========================="); //_hubContext.Clients.User(userId.ToString()).SendAsync("ReceiveMessagePrivate", $"{counter}: {DateTime.Now}"); _hubContext.Clients.User(userId.ToString()).SendAsync("ReceiveMessagePrivate", JsonConvert.SerializeObject(new SocketObject() { Timestamp = GlobalSettings.CURRENT_DATETIME_AS_STRING, Object = new { Counter = counter }, Message = "Tick" })); counter++; }, intervalInMilliseconds: 1000, // fire every one seconds.. maxIterations: 20, periodicTaskCreationOptions: TaskCreationOptions.RunContinuationsAsynchronously); // for a total of 20 iterations... await perdiodicTask.ContinueWith(_ => { Console.WriteLine("===========================End========================="); _competitionQueryProcessor.AnswerQuestion(questionid, 0, userId); //_hubContext.Clients.User(userId.ToString()).SendAsync("ReceiveMessagePrivate", $"User did't answer, result is 0 {DateTime.Now}"); _hubContext.Clients.User(userId.ToString()).SendAsync("ReceiveMessagePrivate", JsonConvert.SerializeObject(new SocketObject() { Timestamp = GlobalSettings.CURRENT_DATETIME_AS_STRING, Object = new { Result = 0 }, Message = "User did't answer" })); }); return(true); }
public void StartScheduler() { //Delay first execution until expected time has passed Task.Delay(interval * 1000).Wait(); Task schedulerTask = PeriodicTaskFactory.Start( () => AddSegmentsToQueue(), intervalInMilliseconds: interval * 1000, cancelToken: cancelTokenSource.Token); }
public void Start() { _wrapperAdapter .TaskDelay(_firstPushWindow * 1000) .ContinueWith((t) => { SendBulkEvents(); PeriodicTaskFactory.Start(() => { SendBulkEvents(); }, _interval * 1000, _cancellationTokenSource.Token); }); }
public void Start() { var periodicTask = PeriodicTaskFactory.Start(async() => { await FetchSplits(); }, intervalInMilliseconds: _interval * 1000, cancelToken: _cancelTokenSource.Token); }
public void Start() { Task periodicTask = PeriodicTaskFactory.Start(() => { RefreshSplits(); }, intervalInMilliseconds: interval * 1000, cancelToken: cancelTokenSource.Token); }
private void MonitorJobStatus(Action job, string id, CancellationToken token) { var monitor = PeriodicTaskFactory.Start(job, intervalInMilliseconds: 2000, duration: 60000 * 60, // wait for max. 1 hour until abort cancelToken: token); monitor.ContinueWith(_ => { JobCompletedEvent?.Invoke(id); }); }
protected async Task PeriodicTaskFactoryCore() { int expectedChickenNumber = 2; int actualChickenNumber = 0; await PeriodicTaskFactory.Start( () => { actualChickenNumber = IncrementChickenNumber(actualChickenNumber); }, MockData.RepeatIntervalInMillisecs, MockData.StartDelayInMillisecs, MockData.Duration, expectedChickenNumber).ConfigureAwait(false); Assert.Equal(expectedChickenNumber, actualChickenNumber); }
public void Initialize() { if (IsInitialized) { return; } _dataContext = new DataContext(_configurationService.Get <ISQLiteConfiguration>()); _dataContext.ChangeTracker.StateChanged += (s, e) => { AccountIdentity accountIdentity = e.Entry.Entity as AccountIdentity; }; _dataContext.Database.EnsureCreated(); _dataContext.EnsureConfigurationCompleted(); PeriodicTaskFactory.Start(() => { if (_isSaving) { return; } lock (_sync) { if (_isSaving) { return; } _isSaving = true; try { if (_dataContext.ChangeTracker.HasChanges()) { _dataContext.SaveChanges(); } } catch (Exception ex) { _logger.Error("Failure during saving data to database", ex); } finally { _isSaving = false; } } }, 1000, cancelToken: _cancellationTokenSource.Token, periodicTaskCreationOptions: System.Threading.Tasks.TaskCreationOptions.LongRunning); IsInitialized = true; }
private void SynchronizationStateChanged(string propName) { _cancellationTokenSource?.Cancel(); _cancellationTokenSource = new CancellationTokenSource(); PeriodicTaskFactory.Start(() => { IEnumerable <RegistryFullBlock> registryFullBlocks = _syncRegistryMemPool.GetRegistryBlocks(); CreateAndDistributeCombinedBlock(registryFullBlocks); DistributeAndSaveFullBlock(registryFullBlocks); }, _cyclePeriodMsec * _synchronizationConfiguration.TotalNodes, _cyclePeriodMsec * _synchronizationConfiguration.Position, cancelToken: _cancellationTokenSource.Token, periodicTaskCreationOptions: TaskCreationOptions.LongRunning); }
private void ScheduleMaxTimeNoTestConReceivedFuture() { if (maxTimeNoTestConReceivedFuture != null) { maxTimeNoTestConReceivedFuture.Cancel(); maxTimeNoTestConReceivedFuture = null; } maxTimeNoTestConReceivedFuture = PeriodicTaskFactory.Start(() => { Close(); ConnectionClosed?.Invoke(new IOException( "The maximum time that no test frame confirmation was received (t1) has been exceeded. t1 = " + settings.MaxTimeNoAckReceived + "ms")); }, settings.MaxTimeNoAckReceived); }
public void Initialize() { if (IsInitialized) { return; } _dataContext.Database.EnsureCreated(); _dataContext.EnsureConfigurationCompleted(); PeriodicTaskFactory.Start(() => { if (_isSaving) { return; } lock (_sync) { if (_isSaving) { return; } _isSaving = true; try { if (_dataContext.ChangeTracker.HasChanges()) { _dataContext.SaveChanges(); } } catch (Exception ex) { _logger.Error("Failure during saving data to database", ex); } finally { _isSaving = false; } } }, 1000, cancelToken: _cancellationTokenSource.Token); IsInitialized = true; }
public void PeriodicTaskFactory_TwoCreates_RunInParallel() { var factory = new PeriodicTaskFactory(); var listA = new List <long>(); var listB = new List <long>(); var stopwatchA = new Stopwatch(); var stopwatchB = new Stopwatch(); stopwatchA.Start(); stopwatchB.Start(); factory.Create(TimeSpan.FromMilliseconds(50), () => listA.Add(stopwatchA.ElapsedMilliseconds)); factory.Create(TimeSpan.FromMilliseconds(100), () => listB.Add(stopwatchA.ElapsedMilliseconds)); Task.Delay(140).Wait(); Assert.AreEqual(3, listA.Count); // 0ms, ~50+ ms, ~100+ ms Assert.AreEqual(2, listB.Count); // 0ms, ~100+ ms }
public void Start() { Task.Factory.StartNew(() => { while (true) { if (_gates.IsSDKReady(0)) { //Delay first execution until expected time has passed var intervalInMilliseconds = _interval * 1000; _wrappedAdapter.TaskDelay(intervalInMilliseconds).Wait(); PeriodicTaskFactory.Start(() => AddSegmentsToQueue(), intervalInMilliseconds, _cancelTokenSource.Token); break; } _wrappedAdapter.TaskDelay(500).Wait(); } }); }
public async Task ReadTaskAsync() { if (_periodicReadRateCalculator == null) { _periodicReadRateCalculator = PeriodicTaskFactory.Run(CalculateReadRate, TimeSpan.FromSeconds(5), _periodicReadRateCalculatorCts.Token); } var keyCount = 0; lock (_lock) { keyCount = _keys.Count; } Task[] tasks = new Task[keyCount]; var keys = _keys.GetRange(0, _taskPool); while (keys.Count > 0) { keys = _keys.GetRange(0, Math.Min(_keys.Count, _taskPool)); int i = 0; foreach (var key in keys) { tasks[i++] = Task.Factory.StartNew(async() => { var response = await _databaseClient.SendReadRequestAsync(key); if (!response.IsSuccessStatusCode) { Console.WriteLine($"{key} - {response.StatusCode}"); } else { Interlocked.Increment(ref _readCount); } }); } } await Task.WhenAll(tasks); }
private void cmbAutoRefrsh_SelectionChanged(object sender, SelectionChangedEventArgs e) { var delay = (int)cmbAutoRefrsh.SelectedValue; if (_stateTimer != null) { _stateTimer.CancelToken = new CancellationToken(true); } if (delay > 0) { _stateTimer = new PeriodicTaskFactory((task) => { //var dataSource = _viewer.GetEventLogData(); this.Dispatcher.BeginInvoke(new Action(InsertNewDataToGrid)); }, new TimeSpan(0, 0, delay), new TimeSpan(0, 0, delay)); _stateTimer.Start(); } }
public async Task <bool> GetCurrentUser() { var userId = _context.User.Id.ToString(); var counter = 1; Task perdiodicTask = PeriodicTaskFactory.Start(() => { Console.WriteLine($"===========================Begin({counter})========================="); _hubContext.Clients.User(userId).SendAsync("ReceiveMessagePrivate", $"{counter}: {DateTime.Now}"); counter++; }, intervalInMilliseconds: 1000, // fire every one seconds.. maxIterations: 10, periodicTaskCreationOptions: TaskCreationOptions.RunContinuationsAsynchronously); // for a total of 20 iterations... await perdiodicTask.ContinueWith(_ => { Console.WriteLine("===========================End========================="); _hubContext.Clients.User(userId).SendAsync("ReceiveMessagePrivate", $"ENDDDDDDDDD: {DateTime.Now}"); }); return(true); }
public void Send() { Task perdiodicTask = PeriodicTaskFactory.Start(() => { // Console.WriteLine(DateTime.Now); List <FlyModel> bjModelTemp = new List <FlyModel>(); List <FlyModel> shModelTemp = new List <FlyModel>(); List <FlyModel> gzModelTemp = new List <FlyModel>(); GetData(ref bjModelTemp, ref shModelTemp, ref gzModelTemp); Clients.All.getFlyMsgSend(bjModelTemp, shModelTemp, gzModelTemp); }, intervalInMilliseconds: 5000// fire every two seconds... ); //List<FlyModel> bjModelTemp = new List<FlyModel>(); //List<FlyModel> shModelTemp = new List<FlyModel>(); //List<FlyModel> gzModelTemp = new List<FlyModel>(); //GetData(ref bjModelTemp, ref shModelTemp, ref gzModelTemp); //Clients.All.getFlyMsgSend(bjModelTemp, shModelTemp, gzModelTemp); }
private void ResetMaxIdleTimeTimer() { if (maxIdleTimeTimerFuture != null) { maxIdleTimeTimerFuture.Cancel(); maxIdleTimeTimerFuture = null; } maxIdleTimeTimerFuture = PeriodicTaskFactory.Start(() => { try { writer.Write(TestfrActBuffer, 0, TestfrActBuffer.Length); writer.Flush(); } catch (Exception) { // ignored } ScheduleMaxTimeNoTestConReceivedFuture(); }, settings.MaxIdleTime); }
public async Task WriteTaskAsync() { if (_periodicWriteRateCalculator == null) { _periodicWriteRateCalculator = PeriodicTaskFactory.Run(CalculateWriteRate, TimeSpan.FromSeconds(5), _periodicWriteRateCalculatorCts.Token); } Task[] tasks = new Task[_taskPool]; var rand = new Random(); for (int i = 0; i < _taskPool; i++) { var key = Guid.NewGuid().ToString(); var value = rand.Next(Int32.MaxValue).ToString(); tasks[i] = Task.Factory.StartNew(async() => { var response = await _databaseClient.SendWriteRequestAsync(key, value); if (!response.IsSuccessStatusCode) { Console.WriteLine($"{key} - {response.StatusCode}"); } else { lock (_lock) { _keys.Add(key); } Interlocked.Increment(ref _writeCount); } }); } await Task.WhenAll(tasks); }
public void Start() { PeriodicTaskFactory.Start(() => { SendBulkImpressions(); }, interval * 1000, cancellationTokenSource.Token); }
public PeriodicTaskConsumer(ILogger logger, PeriodicTaskFactory factory) { this.factory = factory; this.logger = logger; }
public void Start() { PeriodicTaskFactory.Start(() => { SendBulkImpressionsCount(); _running = true; }, CounterRefreshRateSeconds * 1000, _cancellationTokenSource.Token); }
public void StartPeriodic(Action action, int intervalInMilliseconds, CancellationTokenSource cancellationToken, string description) { _log.Debug($"Starting Periodic Task: {description}"); PeriodicTaskFactory.Start(action, intervalInMilliseconds, cancellationToken.Token); }