elsa-core/src/modules/Elsa.Workflows.Runtime/Services/LocalBackgroundActivityScheduler.cs

31 lines
1.3 KiB
C#
Raw Normal View History

2023-04-13 18:05:14 +00:00
using Elsa.Mediator.Contracts;
using Microsoft.Extensions.DependencyInjection;
namespace Elsa.Workflows.Runtime.Services;
/// <summary>
/// Invokes activities from a background worker within the context of its workflow instance using a local background worker.
/// </summary>
public class LocalBackgroundActivityScheduler(IJobQueue jobQueue, IServiceScopeFactory scopeFactory) : IBackgroundActivityScheduler
{
/// <inheritdoc />
2023-04-13 18:05:14 +00:00
public Task<string> ScheduleAsync(ScheduledBackgroundActivity scheduledBackgroundActivity, CancellationToken cancellationToken = default)
{
var jobId = jobQueue.Enqueue(async ct => await InvokeBackgroundActivity(scheduledBackgroundActivity, ct));
2023-04-13 18:05:14 +00:00
return Task.FromResult(jobId);
}
/// <inheritdoc />
public Task CancelAsync(string jobId, CancellationToken cancellationToken = default)
{
jobQueue.Cancel(jobId);
2023-04-13 18:05:14 +00:00
return Task.CompletedTask;
}
private async Task InvokeBackgroundActivity(ScheduledBackgroundActivity scheduledBackgroundActivity, CancellationToken cancellationToken)
{
using var scope = scopeFactory.CreateScope();
var backgroundActivityInvoker = scope.ServiceProvider.GetRequiredService<IBackgroundActivityInvoker>();
await backgroundActivityInvoker.ExecuteAsync(scheduledBackgroundActivity, cancellationToken);
}
}