NServiceBus.AsyncTimer.Start C# (CSharp) Method

Start() public method

public Start ( Func callback, System.TimeSpan interval, Action errorCallback ) : void
callback Func
interval System.TimeSpan
errorCallback Action
return void
        public void Start(Func<Task> callback, TimeSpan interval, Action<Exception> errorCallback)
        {
            tokenSource = new CancellationTokenSource();
            var token = tokenSource.Token;

            task = Task.Run(async () =>
            {
                while (!token.IsCancellationRequested)
                {
                    try
                    {
                        await Task.Delay(interval, token).ConfigureAwait(false);
                        await callback().ConfigureAwait(false);
                    }
                    catch (OperationCanceledException)
                    {
                        // nop
                    }
                    catch (Exception ex)
                    {
                        errorCallback(ex);
                    }
                }
            }, CancellationToken.None);
        }

Usage Example

 void StartHeartbeats()
 {
     Logger.Debug($"Start sending heartbeats every {heartbeatInterval}");
     heartbeatTimer = new AsyncTimer();
     heartbeatTimer.Start(SendHeartbeatMessage, heartbeatInterval, e => { });
 }
AsyncTimer