public async Task StartStop_DelayFirstTick() { var ticks = 0; // Verify that basic start/stop operations work when // delaying the first tick callback. using (var timer = new AsyncTimer( async() => { ticks++; await Task.CompletedTask; })) { Assert.False(timer.IsRunning); await Task.Delay(TimeSpan.FromSeconds(1)); Assert.False(timer.IsRunning); Assert.Equal(0, ticks); timer.Start(TimeSpan.FromSeconds(1), delayFirstTick: true); await Task.Delay(TimeSpan.FromSeconds(4.5)); Assert.True(ticks == 4); timer.Stop(); ticks = 0; await Task.Delay(TimeSpan.FromSeconds(4.5)); Assert.True(ticks == 0); } }
private void Initialize() { // Basic initialization ChannelHost.Start(); hostStarted = true; channels = new Dictionary <string, TInternal>(); channelQueue = new LimitedQueue <TInternal>(maxAcceptedChannels); acceptQueue = new Queue <AsyncResult <TInternal, object> >(); waitQueue = new Queue <AsyncResult <bool, object> >(); // Register the endpoint with the router. SessionHandlerInfo sessionInfo; sessionInfo = this.GetSessionHandlerInfo(); sessionMode = sessionInfo != null && sessionInfo.SessionType == typeof(DuplexSession); if (sessionMode) { ChannelHost.Router.Dispatcher.AddLogical(new MsgHandlerDelegate(OnReceive), ep, typeof(DuplexSessionMsg), false, sessionInfo); } else { ChannelHost.Router.Dispatcher.AddLogical(new MsgHandlerDelegate(OnReceive), ep, typeof(WcfEnvelopeMsg), false, sessionInfo); } // Start the background task timer arBkTimer = AsyncTimer.BeginTimer(bkTaskInterval, onBkTask, null); }
public void Start() { if (paused) { paused = false; } else { _tcpServer = new TcpServer { Port = _config.DevServer_TcpPort, ReceiveTimeout = _config.TcpResponseTimeout / 2, SendTimeout = _config.TcpResponseTimeout / 2, ThreadName = "DevServer_ESP_TCP", }; _tcpServer.GotNewClient += GotNewClient; _tcpServer.Start(); DateTimeService.Instance.HourChanged += OnHourChanged; _scanTimer = new AsyncTimer(_config.DeviceScanTime); _scanTimer.CallBack += Scan_CallBack; _scanTimer.Start(); } }
public void Execute(DocumentDatabase database) { var deleteFrequencyInSeconds = RavenBootstrapper.Settings.ExpirationProcessTimerInSeconds; if (deleteFrequencyInSeconds == 0) { return; } var due = TimeSpan.FromSeconds(deleteFrequencyInSeconds); var deletionBatchSize = RavenBootstrapper.Settings.ExpirationProcessBatchSize; logger.Info("Running deletion of expired documents every {0} seconds", deleteFrequencyInSeconds); logger.Info("Deletion batch size set to {0}", deletionBatchSize); logger.Info("Retention period for errors is {0}", RavenBootstrapper.Settings.ErrorRetentionPeriod); var auditRetention = RavenBootstrapper.Settings.AuditRetentionPeriod; if (auditRetention.HasValue) { logger.Info("Retention period for audits and saga history is {0}", RavenBootstrapper.Settings.AuditRetentionPeriod); } timer = new AsyncTimer( token => ExpiredDocumentsCleaner.RunCleanup(deletionBatchSize, database, RavenBootstrapper.Settings, token), due, due, e => { logger.ErrorException("Error when trying to find expired documents", e); }); }
public async Task It_continues_to_run_after_an_error() { var callbackInvokedAfterError = new TaskCompletionSource <bool>(); var fail = true; var exceptionThrown = false; var timer = new AsyncTimer(); timer.Start((time, token) => { if (fail) { fail = false; throw new Exception("Simulated!"); } Assert.IsTrue(exceptionThrown); callbackInvokedAfterError.SetResult(true); return(Task.FromResult(0)); }, TimeSpan.Zero, e => { exceptionThrown = true; }, Task.Delay); Assert.IsTrue(await callbackInvokedAfterError.Task.ConfigureAwait(false)); }
public async Task Stop_cancels_token_while_waiting() { var timer = new AsyncTimer(); var waitCanceled = false; var delayStarted = new TaskCompletionSource <bool>(); timer.Start( callback: (_, _) => throw new Exception("Simulated!"), interval: TimeSpan.FromDays(7), errorCallback: _ => { // noop }, delayStrategy: async(delayTime, token) => { delayStarted.SetResult(true); try { await Task.Delay(delayTime, token); } catch (OperationCanceledException) { waitCanceled = true; } }); await delayStarted.Task; await timer.Stop(); Assert.True(waitCanceled); }
public async Task Stop_cancels_token_while_in_callback() { var timer = new AsyncTimer(); var callbackCancelled = false; var callbackStarted = new TaskCompletionSource <bool>(); var stopInitiated = new TaskCompletionSource <bool>(); timer.Start(async(time, token) => { callbackStarted.SetResult(true); await stopInitiated.Task.ConfigureAwait(false); if (token.IsCancellationRequested) { callbackCancelled = true; } }, TimeSpan.Zero, e => { //noop }, Task.Delay); await callbackStarted.Task.ConfigureAwait(false); var stopTask = timer.Stop(); stopInitiated.SetResult(true); await stopTask.ConfigureAwait(false); Assert.IsTrue(callbackCancelled); }
public async Task Stop_cancels_token_while_waiting() { var timer = new AsyncTimer(); var waitCancelled = false; var delayStarted = new TaskCompletionSource <bool>(); timer.Start((time, token) => { throw new Exception("Simulated!"); }, TimeSpan.FromDays(7), e => { //noop }, async(delayTime, token) => { delayStarted.SetResult(true); try { await Task.Delay(delayTime, token).ConfigureAwait(false); } catch (OperationCanceledException) { waitCancelled = true; } }); await delayStarted.Task.ConfigureAwait(false); await timer.Stop().ConfigureAwait(false); Assert.IsTrue(waitCancelled); }
public async Task It_continues_to_run_after_an_error() { var callbackInvokedAfterError = new TaskCompletionSource <bool>(); var fail = true; var exceptionThrown = false; var timer = new AsyncTimer(); timer.Start( callback: (_, _) => { if (fail) { fail = false; throw new Exception("Simulated!"); } Assert.True(exceptionThrown); callbackInvokedAfterError.SetResult(true); return(Task.FromResult(0)); }, interval: TimeSpan.Zero, errorCallback: _ => { exceptionThrown = true; }, delayStrategy: Task.Delay); Assert.True(await callbackInvokedAfterError.Task); }
static void Main(string[] args) { Action timerAct = delegate() { Console.WriteLine("This is within the Timer class"); }; Action mainAct = delegate() { Console.WriteLine("This is within the Main class"); }; AsyncTimer timer = new AsyncTimer(10, 30000, timerAct); Thread thread = new Thread(new ThreadStart(timer.Run)); thread.Start(); for (int i = 0; i < 10; i++) { int count = 0; while (count < 30000) { count++; } mainAct.Invoke(); } }
public DedupeCleaner(Func <CancellationToken, Task> cleanup, Action <Exception> criticalError, TimeSpan frequencyToRunCleanup, AsyncTimer timer) { this.cleanup = cleanup; this.frequencyToRunCleanup = frequencyToRunCleanup; this.timer = timer; this.criticalError = criticalError; }
public async Task Stop_waits_for_callback_to_complete() { var timer = new AsyncTimer(); var callbackCompleted = new TaskCompletionSource <bool>(); var callbackTaskStarted = new TaskCompletionSource <bool>(); timer.Start((time, token) => { callbackTaskStarted.SetResult(true); return(callbackCompleted.Task); }, TimeSpan.Zero, e => { //noop }, Task.Delay); await callbackTaskStarted.Task.ConfigureAwait(false); var stopTask = timer.Stop(); var delayTask = Task.Delay(1000); var firstToComplete = await Task.WhenAny(stopTask, delayTask).ConfigureAwait(false); Assert.AreEqual(delayTask, firstToComplete); callbackCompleted.SetResult(true); await stopTask.ConfigureAwait(false); }
public void AsyncTimer_CancelAll() { DateTime start = SysTime.Now; IAsyncResult ar1, ar2; ar1 = AsyncTimer.BeginTimer(TimeSpan.FromSeconds(20), null, null); ar2 = AsyncTimer.BeginTimer(TimeSpan.FromSeconds(30), null, null); Thread.Sleep(5000); AsyncTimer.CancelTimer(ar1); AsyncTimer.CancelTimer(ar2); try { AsyncTimer.EndTimer(ar1); Assert.Fail("Expected a CancelException"); AsyncTimer.EndTimer(ar2); Assert.Fail("Expected a CancelException"); } catch (CancelException) { } Assert.IsTrue(SysTime.Now >= start + TimeSpan.FromSeconds(5) - SysTime.Resolution); Assert.IsTrue(SysTime.Now <= start + TimeSpan.FromSeconds(6) - SysTime.Resolution); }
public async Task Stop_cancels_token_while_in_callback() { var callbackCanceled = false; var callbackStarted = new TaskCompletionSource <bool>(); var stopInitiated = new TaskCompletionSource <bool>(); var timer = new AsyncTimer( callback: async(time, token) => { callbackStarted.SetResult(true); await stopInitiated.Task; if (token.IsCancellationRequested) { callbackCanceled = true; } }, interval: TimeSpan.Zero); await callbackStarted.Task; var stopTask = timer.DisposeAsync(); stopInitiated.SetResult(true); await stopTask; Assert.True(callbackCanceled); }
public void AsyncTimer_PollInterval() { DateTime start = SysTime.Now; object state; IAsyncResult ar; ar = AsyncTimer.BeginTimer(TimeSpan.FromSeconds(1), null, "4"); state = ar.AsyncState; AsyncTimer.EndTimer(ar); Assert.IsTrue(SysTime.Now - start >= TimeSpan.FromSeconds(1) - SysTime.Resolution); Assert.AreEqual("4", state); AsyncTimer.PollInterval = TimeSpan.FromSeconds(1); start = SysTime.Now; ar = AsyncTimer.BeginTimer(TimeSpan.FromSeconds(1), null, "5"); state = ar.AsyncState; AsyncTimer.EndTimer(ar); Assert.IsTrue(SysTime.Now - start >= TimeSpan.FromSeconds(1) - SysTime.Resolution); Assert.AreEqual("5", state); }
public async Task Dispose() { // Verify that [Dispose()] stops the timer. var ticks = 0; var timer = new AsyncTimer( async() => { ticks++; await Task.CompletedTask; }); timer.Start(TimeSpan.FromSeconds(1)); await Task.Delay(TimeSpan.FromSeconds(4.5)); Assert.True(ticks == 5); timer.Dispose(); ticks = 0; await Task.Delay(TimeSpan.FromSeconds(4.5)); Assert.True(ticks == 0); // Verify that calling [Dispose()] on an already disposed timer // does not throw an exception. timer.Dispose(); }
/// <summary> /// Internal background task method. /// </summary> /// <param name="state">Not used.</param> private void OnBkTask(object state) { DateTime now = SysTime.Now; AsyncTimer.EndTimer(arBkTimer); using (TimedLock.Lock(this)) { try { // Give derived classes a chance to perform any necessary // background tasks. OnBkTask(); } catch (Exception e) { SysLog.LogException(e); } finally { // Schedule the next timer if this functionality is // still enabled. if (onBkTask != null) { arBkTimer = AsyncTimer.BeginTimer(bkTaskInterval, onBkTask, null); } } } }
public async Task StartStop() { // Verify that basic start/stop operations work. var ticks = 0; using (var timer = new AsyncTimer( async() => { ticks++; await Task.CompletedTask; })) { Assert.False(timer.IsRunning); await Task.Delay(TimeSpan.FromSeconds(1)); Assert.Equal(TimeSpan.Zero, timer.Interval); Assert.False(timer.IsRunning); Assert.Equal(0, ticks); timer.Start(TimeSpan.FromSeconds(1)); await Task.Delay(TimeSpan.FromSeconds(4.5)); Assert.True(ticks == 5); Assert.Equal(TimeSpan.FromSeconds(1), timer.Interval); timer.Stop(); ticks = 0; await Task.Delay(TimeSpan.FromSeconds(4.5)); Assert.True(ticks == 0); } }
public async Task Stop_cancels_token_while_in_callback() { var timer = new AsyncTimer(); var callbackCanceled = false; var callbackStarted = new TaskCompletionSource <bool>(); var stopInitiated = new TaskCompletionSource <bool>(); timer.Start( callback: async(_, token) => { callbackStarted.SetResult(true); await stopInitiated.Task; if (token.IsCancellationRequested) { callbackCanceled = true; } }, interval: TimeSpan.Zero, errorCallback: _ => { //noop }, delayStrategy: Task.Delay); await callbackStarted.Task; var stopTask = timer.Stop(); stopInitiated.SetResult(true); await stopTask; Assert.True(callbackCanceled); }
public async Task Stop_waits_for_callback_to_complete() { var timer = new AsyncTimer(); var callbackCompleted = new TaskCompletionSource <bool>(); var callbackTaskStarted = new TaskCompletionSource <bool>(); timer.Start( callback: (_, _) => { callbackTaskStarted.SetResult(true); return(callbackCompleted.Task); }, interval: TimeSpan.Zero, errorCallback: _ => { //noop }, delayStrategy: Task.Delay); await callbackTaskStarted.Task; var stopTask = timer.Stop(); var delayTask = Task.Delay(1000); var firstToComplete = await Task.WhenAny(stopTask, delayTask); Assert.Equal(delayTask, firstToComplete); callbackCompleted.SetResult(true); await stopTask; }
static void Main() { AsyncTimer timer1 = new AsyncTimer(Work1, 1000, 10); timer1.Start(); AsyncTimer timer2 = new AsyncTimer(Work2, 500, 20); timer2.Start(); }
static void Main(string[] args) { Action<int> test = (number) => Console.WriteLine("{0}", number); AsyncTimer asyncTimer = new AsyncTimer(test, 10, 1000); asyncTimer.Run(); }
private void OnAsyncDone(IAsyncResult ar) { AsyncState state = (AsyncState)ar.AsyncState; state.Router.ReplyTo(state.Query, new TestAck("async-complete")); state.Session.OnAsyncFinished(); AsyncTimer.EndTimer(ar); }
protected override Task OnStart(IMessageSession session) { timer = new AsyncTimer(t => Process(t), TimeSpan.Zero, settings.ProcessRetryBatchesFrequency, e => { log.Error("Unhandled exception while processing retry batches", e); }); return(Task.FromResult(0)); }
static void Main() { Action f = testMethod;; AsyncTimer test = new AsyncTimer(f, 10, 500); test.Run(); string testString = Console.ReadLine(); }
/// <summary> /// Start the event processor timer /// </summary> private void StartProcessorTimer(double interval) { if (null != _timer) { return; } _timer = new AsyncTimer(EventsProcessorAsync, interval, _logger, "Events Processor"); }
protected override Task OnStart(IMessageSession session) { if (retries != null) { timer = new AsyncTimer(_ => ProcessRequestedBulkRetryOperations(), interval, interval, e => { log.Error("Unhandled exception while processing bulk retry operations", e); }); } return(Task.FromResult(0)); }
public async Task WaitAsync(double seconds) { AsyncTimer timer = new AsyncTimer(TimeSpan.FromSeconds(seconds)); timer.Start(); await Task.WhenAny(timer.CompletionSource.Task); await Context.Channel.SendMessageAsync($"The timer has timed out. ({Format.Counter(timer.ElapsedTime.TotalSeconds)})"); }
protected override Task OnStart(IMessageSession session) { timer = new AsyncTimer(async _ => { var hasMoreWork = await AdoptOrphanedBatchesAsync().ConfigureAwait(false); return(hasMoreWork ? TimerJobExecutionResult.ScheduleNextExecution : TimerJobExecutionResult.DoNotContinueExecuting); }, TimeSpan.Zero, TimeSpan.FromMinutes(2), e => { log.Error("Unhandled exception while trying to adopt orphaned batches", e); }); return(Task.FromResult(0)); }
public void Start() { timer = new AsyncTimer( Run, TimeSpan.Zero, check.Interval ?? TimeSpan.MaxValue, e => { /* Should not happen */ } ); }
protected override async Task OnStart(IMessageSession session) { await persistence.WarmupMonitoringFromPersistence().ConfigureAwait(false); timer = new AsyncTimer(_ => CheckEndpoints(), TimeSpan.Zero, TimeSpan.FromSeconds(5), e => { log.Error("Exception occurred when monitoring endpoint instances", e); }); }
public ScheduledTask(Func <ScheduledTask, Task> task, DateTime executionTime, ILogger logger, bool recurring = false) { Id = _idCounter++; ExecutionTime = executionTime; Recurring = recurring; _task = task; _logger = logger; _timer = new AsyncTimer(executionTime - DateTime.Now); InitTimer(); }
public static void Main() { AsyncTimer currTimer = new AsyncTimer(PrintSth, 100, 100); currTimer.Run(); for (int i = 0; i < 100; i++) { Console.WriteLine("Main program action!"); Thread.Sleep(100); } }
static void Main() { var printOnConsole = new AsyncTimer(PrintOnConsole, 5, 900000000); printOnConsole.Run(); var printOnFile = new AsyncTimer(PrintOnFile, 10, 5000); printOnFile.Run(); var showMessageBox = new AsyncTimer(ShowMessageBox, 4, 100000); showMessageBox.Run(); }
static void Main() { AsyncTimer aTimer = new AsyncTimer(asyncMethod, 1000, 50); aTimer.Start(); //the code below is for testing asynchronous execution of method: int count = 1000; while (count >= 0) { Thread.Sleep(200); count--; Console.WriteLine(count); } }
public static void Main() { Action<string> method = delegate(string str) { Console.WriteLine(str); Console.Beep(); }; Action<string> method2 = str => Console.WriteLine("Hurry up!"); ; AsyncTimer timer = new AsyncTimer(method, 100, 1000); AsyncTimer timer2 = new AsyncTimer(method2, 100, 1000); timer.Start(); timer2.Start(); }
static void Main(string[] args) { var interestCalculator = new InterestCalculator(500m, 5.6m, 10, GetCompoundInterest); Console.WriteLine(interestCalculator); var compoundInterest = new InterestCalculator(2500m, 7.2m, 15, GetSimpleInterest); Console.WriteLine(compoundInterest); ////////////////// Async Timer //////////////////// AsyncTimer timer1 = new AsyncTimer(Work1, 1000, 10); timer1.Start(); AsyncTimer timer2 = new AsyncTimer(Work2, 500, 20); timer2.Start(); }
static void Main() { // Chast ot resheniqta na problemite tuk sa vzeti ot foruma /* Solution for Problem 1/Interest Calculator/ */ var interest = new InterestCalculator(500m, 5.6m, 10, GetCompoundInterest); Console.WriteLine(interest); var compoundInterest = new InterestCalculator(2500m, 7.2m, 15, GetSimpleInterest); Console.WriteLine(compoundInterest); /* Solution for Problem 2/Async Timer/ */ AsyncTimer timer1 = new AsyncTimer(Work1, 1000, 10); timer1.Start(); AsyncTimer timer2 = new AsyncTimer(Work2, 500, 20); timer2.Start(); /* Solution for Problem 3/Student Class/ */ var student = new Student("Go6o", 17); student.Name = "Zara"; student.Age = 69; }
static void Main() { AsyncTimer timer = new AsyncTimer(writeSeconds, 500, 20); timer.Start(); }
static void Main() { var timer = new AsyncTimer(TestMethod, 4, 500); timer.Run(); }