66 lines
2.5 KiB
C#
66 lines
2.5 KiB
C#
using System;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Hosting;
|
|
using Serilog;
|
|
using NCrontab;
|
|
using LCU.Api.Internal.MaidBotApi.Services;
|
|
using LCU.Api.Internal.MaidBotApi.Configurations;
|
|
namespace LCU.API.Internal.MaidBotApi.HostedService;
|
|
|
|
public class SchedulerHostedService : BackgroundService
|
|
{
|
|
private readonly ApiConfiguration _apiConfiguration;
|
|
private readonly IServiceScopeFactory _scopeFactory;
|
|
|
|
private readonly CrontabSchedule _schedule;
|
|
private DateTime _nextScheduleRun;
|
|
public const string DefaultScheduleCronPattern = "*/5 * * * *";
|
|
|
|
private CancellationToken _cancellationToken;
|
|
|
|
public SchedulerHostedService(IServiceScopeFactory scopeFactory,
|
|
ApiConfiguration apiConfiguration)
|
|
{
|
|
_scopeFactory = scopeFactory;
|
|
_apiConfiguration = apiConfiguration;
|
|
|
|
var cron = (_apiConfiguration?.BatchSchedulerCron) ?? DefaultScheduleCronPattern;
|
|
_schedule = CrontabSchedule.Parse(cron);
|
|
_nextScheduleRun = _schedule.GetNextOccurrence(DateTime.Now);
|
|
|
|
_cancellationToken = new CancellationToken();
|
|
}
|
|
|
|
protected override async Task ExecuteAsync(CancellationToken cancellationToken)
|
|
{
|
|
Log.Information("MaidBot Scheduler Hosted Service is starting.");
|
|
_cancellationToken = cancellationToken;
|
|
try
|
|
{
|
|
do
|
|
{
|
|
if (_apiConfiguration.FeatureFlags.RunScheduler && DateTime.Now > _nextScheduleRun)
|
|
{
|
|
using var scope = _scopeFactory.CreateScope();
|
|
await Task.Run(async () => await scope.ServiceProvider.GetRequiredService<ILogDistributionService>().HandleLogDistribution());
|
|
|
|
_nextScheduleRun = _schedule.GetNextOccurrence(DateTime.Now);
|
|
}
|
|
|
|
await Task.Delay(5000, cancellationToken); //5 seconds delay
|
|
} while (!cancellationToken.IsCancellationRequested);
|
|
}
|
|
catch (TaskCanceledException taskCanceledException) when (_cancellationToken.IsCancellationRequested)
|
|
{
|
|
Log.Information(taskCanceledException, "MaidBot Scheduler Hosted Service was shut down normally.");
|
|
}
|
|
catch (Exception exception)
|
|
{
|
|
Log.Error(exception, "Error trying to startup main thread for MaidBot Scheduler Hosted Service");
|
|
}
|
|
|
|
Log.Information("MaidBot Scheduler Hosted Service is stopping.");
|
|
}
|
|
} |