Skip to content

Instantly share code, notes, and snippets.

@mikeminutillo
Last active May 24, 2017 08:52
Show Gist options
  • Save mikeminutillo/44c2ca4885f949373cd7938e5a4eb80f to your computer and use it in GitHub Desktop.
Save mikeminutillo/44c2ca4885f949373cd7938e5a4eb80f to your computer and use it in GitHub Desktop.
Run a process every midnight that gathers some data and publishes an event
// Used to kick off the scheduler whenever the endpoint starts
class StartSchedulerCommand : ICommand
{
public Guid Key { get; set; }
}
// The scheduler saga sends one of these every midnight
class RunProcessCommand : ICommand
{
}
// The actual event that you want to fire
class SomeEvent : IEvent
{
}
class StartScheduler : IWantToRunWhenBusStartsAndStops
{
public IBus Bus { get; set; }
public void Start()
{
Bus.SendLocal(new StartSchedulerCommand
{
// NOTE: This has to be deterministic so that it always triggers the same saga
Key = new Guid("6c99336f-9961-4a6f-8b77-b1a438cd9cdc")
});
}
public void Stop() { }
}
class SagaBasedSchedulerSagaData : ContainSagaData
{
[Unique]
public Guid Key { get; set; }
public DateTime? NextRun { get; set; }
}
class SagaBasedScheduler : Saga<SagaBasedSchedulerSagaData>,
IAmStartedByMessages<StartSchedulerCommand>,
IHandleTimeouts<SagaBasedScheduler.NextRunTimeout>
{
protected override void ConfigureHowToFindSaga(SagaPropertyMapper<SagaBasedSchedulerSagaData> mapper)
{
mapper.ConfigureMapping<StartSchedulerCommand>(m => m.Key)
.ToSaga(s => s.Key);
}
public void Handle(StartSchedulerCommand message)
{
ScheduleNextRun();
}
public class NextRunTimeout { }
public void Timeout(NextRunTimeout state)
{
Bus.SendLocal(new RunProcessCommand());
ScheduleNextRun();
}
private void ScheduleNextRun()
{
if (Data.NextRun.GetValueOrDefault() < DateTime.Now)
{
var midnightTonight = DateTime.Today.AddDays(1);
Data.NextRun = midnightTonight;
RequestTimeout<NextRunTimeout>(midnightTonight);
}
}
}
class RunProcessCommandHandler : IHandleMessages<RunProcessCommand>
{
public IBus Bus { get; set; }
public void Handle(RunProcessCommand message)
{
// Gather Data
Bus.Publish(new SomeEvent { /* Gathered Data */ });
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment