Skip to content

Instantly share code, notes, and snippets.

@ReubenBond
Created January 17, 2024 16:46
Show Gist options
  • Save ReubenBond/8dc47f68634faafe334fadc6f5444ad0 to your computer and use it in GitHub Desktop.
Save ReubenBond/8dc47f68634faafe334fadc6f5444ad0 to your computer and use it in GitHub Desktop.
Orleans Grain Long Running Reminder
#nullable enable
using Orleans.Runtime;
namespace MyGrains;
public class MyLongRunningReminderGrain : Grain, IRemindable
{
private readonly CancellationTokenSource _shutdownCancellation = new();
private Task? _backgroundTask;
public Task ReceiveReminder(string reminderName, TickStatus status)
{
if (_backgroundTask is null or { IsCompleted: true })
{
_backgroundTask = ProcessBackgroundTask();
}
return Task.CompletedTask;
}
private async Task ProcessBackgroundTask()
{
// It's polite to yield immediately, since we're starting background work.
await Task.Yield();
while (!_shutdownCancellation.IsCancellationRequested)
{
// Do work here...
await Task.Delay(1_000);
}
}
public override async Task OnDeactivateAsync(DeactivationReason reason, CancellationToken cancellationToken)
{
_shutdownCancellation.Cancel();
if (_backgroundTask is { } task && !task.IsCompleted)
{
// Wait for the background task to complete, but don't wait indefinitely.
await task.WaitAsync(cancellationToken);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment