Allow to configure JobRunner worker count

This commit is contained in:
Thomas Trummer 2025-03-14 10:14:47 +01:00
parent d0d3ab1c1c
commit 84be58fceb
3 changed files with 23 additions and 11 deletions

View file

@ -54,8 +54,14 @@ public static class DependencyInjectionExtensions
.AddSingleton<INotificationsChannel, NotificationsChannel>()
.AddSingleton<ICommandsChannel, CommandsChannel>()
.AddSingleton<IJobsChannel, JobsChannel>()
.AddSingleton<IJobQueue, JobQueue>()
.AddHostedService<JobRunnerHostedService>()
.AddSingleton<IJobQueue, JobQueue>()
.AddHostedService(sp =>
{
using var scope = sp.CreateScope();
var options = scope.ServiceProvider.GetRequiredService<IOptions<MediatorOptions>>().Value;
return ActivatorUtilities.CreateInstance<JobRunnerHostedService>(scope.ServiceProvider, options.JobWorkerCount);
})
.AddHostedService(sp =>
{
using var scope = sp.CreateScope();

View file

@ -9,13 +9,14 @@ namespace Elsa.Mediator.HostedServices;
/// </summary>
public class JobRunnerHostedService : BackgroundService
{
private const int WorkerCount = 4;
private readonly int _workerCount;
private readonly IJobsChannel _jobsChannel;
private readonly ILogger<JobRunnerHostedService> _logger;
/// <inheritdoc />
public JobRunnerHostedService(IJobsChannel jobsChannel, ILogger<JobRunnerHostedService> logger)
{
public JobRunnerHostedService(int workerCount, IJobsChannel jobsChannel, ILogger<JobRunnerHostedService> logger)
{
_workerCount = workerCount;
_jobsChannel = jobsChannel;
_logger = logger;
}
@ -23,9 +24,9 @@ public class JobRunnerHostedService : BackgroundService
/// <inheritdoc />
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
var workers = new Task[WorkerCount];
for (var i = 0; i < WorkerCount; i++)
var workers = new Task[_workerCount];
for (var i = 0; i < _workerCount; i++)
workers[i] = ProcessJobsAsync(stoppingToken);
await Task.WhenAll(workers);

View file

@ -10,12 +10,17 @@ public class MediatorOptions
/// <summary>
/// The max number of workers to process commands.
/// </summary>
public int CommandWorkerCount { get; set; } = 4;
public int CommandWorkerCount { get; set; } = 4;
/// <summary>
/// The max number of workers to process notifications.
/// </summary>
public int NotificationWorkerCount { get; set; } = 4;
public int NotificationWorkerCount { get; set; } = 4;
/// <summary>
/// The max number of workers to process jobs.
/// </summary>
public int JobWorkerCount { get; set; } = 4;
/// <summary>
/// The default publishing strategy to use.