sozsoft-platform/api/src/Sozsoft.Platform.HttpApi.Host/AbpBackgroundWorkerRecurringJobInitializer.cs
2026-06-29 12:37:52 +03:00

60 lines
2 KiB
C#

using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Volo.Abp.BackgroundJobs;
using Volo.Abp.BackgroundWorkers;
using Volo.Abp.DependencyInjection;
using Volo.Abp.OpenIddict.Tokens;
namespace Sozsoft.Platform;
public class AbpBackgroundWorkerRecurringJobInitializer : ITransientDependency
{
private readonly IServiceProvider _serviceProvider;
private readonly IBackgroundWorkerManager _backgroundWorkerManager;
private readonly ILogger<AbpBackgroundWorkerRecurringJobInitializer> _logger;
public AbpBackgroundWorkerRecurringJobInitializer(
IServiceProvider serviceProvider,
IBackgroundWorkerManager backgroundWorkerManager,
ILogger<AbpBackgroundWorkerRecurringJobInitializer> logger)
{
_serviceProvider = serviceProvider;
_backgroundWorkerManager = backgroundWorkerManager;
_logger = logger;
}
public async Task RunAsync(CancellationToken cancellationToken = default)
{
await AddWorkerIfAvailableAsync<BackgroundJobWorker>(
nameof(BackgroundJobWorker),
cancellationToken);
await AddWorkerIfAvailableAsync<TokenCleanupBackgroundWorker>(
nameof(TokenCleanupBackgroundWorker),
cancellationToken);
}
private async Task AddWorkerIfAvailableAsync<TWorker>(
string workerName,
CancellationToken cancellationToken)
where TWorker : class, IBackgroundWorker
{
var worker = _serviceProvider.GetService<TWorker>();
if (worker == null)
{
_logger.LogWarning(
"ABP background worker {WorkerName} could not be resolved from DI. Recurring job was not registered.",
workerName);
return;
}
await _backgroundWorkerManager.AddAsync(worker, cancellationToken);
_logger.LogInformation(
"ABP background worker {WorkerName} recurring job registration has been ensured.",
workerName);
}
}