feat(Program): make Quartz cron schedule configurable via appsettings

- Replaced hardcoded cron expression with configuration-based `Worker:CronExpression`.
- Throws descriptive exception if cron expression is missing.
- Keeps previous worker and DB context setup unchanged.
This commit is contained in:
Developer 02 2025-11-04 15:37:20 +01:00
parent 0a175b9e9d
commit 75e7e9925b
4 changed files with 13 additions and 29 deletions

View File

@ -1,19 +0,0 @@
namespace EnvelopeGenerator.Finalizer.Models;
public class WorkerOptions
{
private double _intervalInMin = 1.0;
public double IntervalInMin {
get => _intervalInMin;
set
{
_intervalInMin = value;
IntervalInMillisecond = Min2Millisecond(value);
}
}
public int IntervalInMillisecond { get; private set; } = Min2Millisecond(1.0);
private static int Min2Millisecond(double min) => Convert.ToInt32(Math.Round(min * 60 * 1000));
}

View File

@ -42,18 +42,23 @@ try
var jobKey = new JobKey(name);
q.AddJob<Worker>(opts => opts.WithIdentity(jobKey));
var expression = config[nameof(Worker) + ":CronExpression"];
if (string.IsNullOrWhiteSpace(expression))
throw new InvalidOperationException(
"Cron expression for the Worker job is not configured. " +
"Please provide a valid cron schedule in the configuration under " +
$"'{nameof(Worker)}:CronExpression'.");
q.AddTrigger(opts => opts
.ForJob(jobKey)
.WithIdentity(name + "-trigger")
.WithCronSchedule("* * * * * ?"));
.WithCronSchedule(expression));
});
builder.Services.AddQuartzHostedService(opt =>
{
opt.WaitForJobsToComplete = true;
});
builder.Services.Configure<WorkerOptions>(config.GetSection("Worker"));
#endregion
#region Add DB Context, EG Inf. and Services

View File

@ -8,21 +8,19 @@ namespace EnvelopeGenerator.Finalizer
{
private readonly ILogger<Worker> _logger;
private readonly WorkerOptions _options;
public Worker(ILogger<Worker> logger, IOptions<WorkerOptions> workerOptions)
public Worker(ILogger<Worker> logger)
{
_logger = logger;
_options = workerOptions.Value;
}
public async Task Execute(IJobExecutionContext context)
public Task Execute(IJobExecutionContext context)
{
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
}
await Task.Delay(_options.IntervalInMillisecond, context.CancellationToken);
return Task.CompletedTask;
}
}
}

View File

@ -1,5 +1,5 @@
{
"Worker": {
"IntervalInMin": 0.01666666666
"CronExpression": "* * * * * ?"
}
}