casa-bot/src/CasaBot/AutoScan/AutoScanApp.cs

74 lines
2.5 KiB
C#

using AutoScan.Jobs;
using AutoScan.Listener;
using AutoScan.Options;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Quartz;
using Quartz.Impl.Matchers;
namespace AutoScan;
public class AutoScanApp
{
private readonly AutoScanOptions _options;
private readonly ILogger<AutoScanApp> _logger;
private readonly IScheduler _scheduler;
private readonly IChainerListenerFactory _chainerListenerFactory;
public AutoScanApp(IOptions<AutoScanOptions> options, ILogger<AutoScanApp> logger, IScheduler scheduler, IChainerListenerFactory chainerListenerFactory)
{
_options = options.Value;
_logger = logger;
_scheduler = scheduler;
_chainerListenerFactory = chainerListenerFactory;
}
public async Task Run(CancellationToken cancellationToken)
{
_logger.LogInformation("AutoScanApp is running...");
var at = DateTime.Now.AddSeconds(10);
var cron = $"{at.Second} {at.Minute} {at.Hour} * * ?";
//var cron = CronFromAt(_options.At);
_logger.LogInformation("Waiting for next scan at {At} [{cron}].", at, cron);
await _scheduler.Start(cancellationToken);
_logger.LogDebug("Scheduler started successfully!");
const string groupName = "ScanGroup";
IJobDetail downloaderJob = JobBuilder.Create<DownloaderJob>()
.WithIdentity("downloader", groupName)
.Build();
//Job with no trigger but tied to the chainer to be executed after the downloader job
IJobDetail scannerJob = JobBuilder.Create<ScannerJob>()
.WithIdentity("scanner", groupName)
.StoreDurably()
.Build();
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("trigger1", groupName)
.WithCronSchedule(cron)
.StartNow()
.Build();
var chainer = _chainerListenerFactory.CreateChainerListener("Scan Chainer");
chainer.AddJobChainLink(downloaderJob.Key, scannerJob.Key);
_scheduler.ListenerManager.AddJobListener(chainer, GroupMatcher<JobKey>.GroupEquals(groupName));
await _scheduler.ScheduleJob(downloaderJob, trigger, cancellationToken);
await _scheduler.AddJob(scannerJob, false, true, cancellationToken);
_logger.LogDebug("Scheduled job successfully!");
}
private string CronFromAt(string at)
{
var parts = at.Split(':');
return $"0 {parts[1]} {parts[0]} * * ?";
}
}