Last active
July 5, 2017 12:55
-
-
Save ramonsmits/351e6b56b783a408a48d92f49cc2f799 to your computer and use it in GitHub Desktop.
NServiceBus scheduler alternative - NServiceBus V6 & NServiceBus.Host V7
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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