Skip to content

Instantly share code, notes, and snippets.

@ramonsmits
Last active July 5, 2017 12:55
Show Gist options
  • Select an option

  • Save ramonsmits/351e6b56b783a408a48d92f49cc2f799 to your computer and use it in GitHub Desktop.

Select an option

Save ramonsmits/351e6b56b783a408a48d92f49cc2f799 to your computer and use it in GitHub Desktop.
NServiceBus scheduler alternative - NServiceBus V6 & NServiceBus.Host V7
var endpointInstance = await Endpoint.Start(endpointConfiguration).ConfigureAwait(false);
// Send a message every 30 seconds
var cancellationTokenSource = new CancellationTokenSource();
var loop = Task.Run(async () =>
{
while (!cancellationTokenSource.IsCancellationRequested)
{
try
{
await endpointInstance.SendLocal(new DoSomething()).ConfigureAwait(false);
await Task.Delay(TimeSpan.FromSeconds(30), cancellationTokenSource.Token).ConfigureAwait(false);
}
catch (Exception ex) // Also catches OperationCanceledException, no issue as while loop is testing on cancellation
{
log.Error("Failure sending DoSomething", ex);
}
}
});
// Before await endpointInstance.Stop()
cancellationTokenSource.Cancel();
await loop.ConfigureAwait(false);
public class SendDoSomethingTask : IWantToRunWhenEndpointStartsAndStops
{
ILog log = LogManager.GetLogger<SendDoSomethingTask>();
Task loop;
CancellationTokenSource cancellationTokenSource;
public Task Start(IMessageSession session)
{
cancellationTokenSource = new CancellationTokenSource();
loop = Task.Run(async () =>
{
while (!cancellationTokenSource.IsCancellationRequested)
{
try
{
await session.SendLocal(new DoSomething()).ConfigureAwait(false);
await Task.Delay(TimeSpan.FromSeconds(5), cancellationTokenSource.Token).ConfigureAwait(false);
}
catch (Exception ex) // Also catches OperationCanceledException, no issue as while loop is testing on cancellation
{
log.Error("Failure sending DoSomething", ex);
}
}
} );
return Task.CompletedTask;
}
public async Task Stop(IMessageSession session)
{
cancellationTokenSource.Cancel();
await loop.ConfigureAwait(false);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment