Path: redb-route/redb.Route.Quartz/CronComponent.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Quartz/CronComponent.cs
----
using Quartz;
using redb.Route.Abstractions;
using redb.Route.Core;
namespace redb.Route.Quartz;
///
/// Cron scheduling component. Scheme: "cron".
/// Fires exchanges on a cron schedule using Quartz.NET CronTrigger.
/// URI: cron://jobName?schedule=0/5 * * * * ?&threads=1
///
[EndpointRole(EndpointRole.Consumer, Hint = "Use it as a From() source.")]
public class CronComponent : ComponentBase
{
///
public override string Scheme => "cron";
///
public override IEndpoint CreateEndpoint(EndpointUri uri)
{
ArgumentNullException.ThrowIfNull(uri);
var options = new CronEndpointOptions();
options.BindFromUri(uri.RawParameters);
ParseGroupAndJob(uri.Path, options);
options.Validate();
return new CronEndpoint(uri, this, options);
}
/// Parses "group/job" or "job" from the URI path into options.
internal static void ParseGroupAndJob(string path, CronEndpointOptions options)
{
var slashIndex = path.IndexOf('/');
if (slashIndex > 0 && slashIndex < path.Length - 1)
{
options.GroupName = path[..slashIndex];
options.JobName = path[(slashIndex + 1)..];
}
else
{
options.JobName = path;
// GroupName defaults to "redb"
}
}
}
///
/// Cron endpoint options.
///
public class CronEndpointOptions : EndpointOptions
{
///
/// Cron expression (Quartz format, 6-7 fields).
/// Example: "0/5 * * * * ?" (every 5 seconds).
///
public string Schedule { get; set; } = string.Empty;
/// Maximum concurrent fires (default: 1).
public int Threads { get; set; } = 1;
// ── Group / Job (parsed from URI path: cron://group/job or cron://job) ──
/// Quartz group name. Parsed from URI path or defaults to "redb".
public string GroupName { get; set; } = "redb";
/// Quartz job/trigger name. Parsed from URI path.
public string JobName { get; set; } = string.Empty;
// ── Job lifecycle ──
/// Delete the job when the route stops (default: true).
public bool DeleteJob { get; set; } = true;
/// Pause the trigger when the route stops instead of deleting (default: false).
/// Cannot be true simultaneously with .
public bool PauseJob { get; set; }
/// Keep the job in the scheduler even if no triggers reference it (default: false).
public bool DurableJob { get; set; }
/// Use PersistJobDataAfterExecution + DisallowConcurrentExecution (default: false).
public bool Stateful { get; set; }
/// Re-execute the job on failover/recovery (default: false).
public bool RecoverableJob { get; set; }
/// Whether to prefix the job name with the endpoint ID (default: false).
public bool PrefixJobNameWithEndpointId { get; set; }
// ── Trigger timing ──
/// Misfire handling strategy (default: trigger-type-specific default).
public QuartzMisfirePolicy MisfireInstruction { get; set; } = QuartzMisfirePolicy.Default;
/// Time zone for the cron trigger (IANA ID, e.g. "Europe/Moscow"). Default: local.
public string? TimeZone { get; set; }
/// Trigger start date (ISO 8601 format). If not set, starts immediately.
public string? StartAt { get; set; }
/// Trigger end date (ISO 8601 format). If not set, runs indefinitely.
public string? EndAt { get; set; }
/// Name of an ICalendar in the route context registry to use for exclusions.
[RegistryReference(typeof(global::Quartz.ICalendar))]
public string? CustomCalendar { get; set; }
/// Delay in ms before the first trigger fire (default: 500).
public long TriggerStartDelay { get; set; } = 500;
///
public override void Validate()
{
if (string.IsNullOrWhiteSpace(Schedule))
throw new ArgumentException("Cron schedule expression is required. Example: '0/5 * * * * ?'", nameof(Schedule));
if (Threads <= 0)
throw new ArgumentOutOfRangeException(nameof(Threads), Threads, "Threads must be greater than 0.");
if (DeleteJob && PauseJob)
throw new ArgumentException("Cannot set both DeleteJob and PauseJob to true.");
// Validate cron expression early
try
{
new CronExpression(Schedule);
}
catch (FormatException ex)
{
throw new ArgumentException($"Invalid cron expression: '{Schedule}'. {ex.Message}", nameof(Schedule), ex);
}
}
}
///
/// Cron endpoint. Consumer-only — fires on a cron schedule.
///
public class CronEndpoint : EndpointBase
{
/// Creates a cron endpoint.
public CronEndpoint(EndpointUri uri, CronComponent component, CronEndpointOptions options)
: base(uri, component, options)
{
}
/// Gets the cron schedule expression.
internal string Schedule => Options.Schedule;
/// Gets the max concurrent threads.
internal int Threads => Options.Threads;
/// Gets the Quartz group name.
internal string GroupName => Options.GroupName;
/// Gets the Quartz job/trigger name.
internal string JobName => Options.JobName;
/// Gets whether to delete the job on route stop.
internal bool DeleteJob => Options.DeleteJob;
/// Gets whether to pause the trigger on route stop.
internal bool PauseJob => Options.PauseJob;
/// Gets whether the job is durable.
internal bool DurableJob => Options.DurableJob;
/// Gets whether the job is stateful (persist data + disallow concurrent).
internal bool Stateful => Options.Stateful;
/// Gets whether the job is recoverable on failover.
internal bool RecoverableJob => Options.RecoverableJob;
/// Gets whether to prefix job name with endpoint ID.
internal bool PrefixJobNameWithEndpointId => Options.PrefixJobNameWithEndpointId;
/// Gets the misfire instruction.
internal QuartzMisfirePolicy MisfireInstruction => Options.MisfireInstruction;
/// Gets the time zone ID for the cron trigger.
internal string? TimeZoneId => Options.TimeZone;
/// Gets the trigger start date string.
internal string? StartAt => Options.StartAt;
/// Gets the trigger end date string.
internal string? EndAt => Options.EndAt;
/// Gets the custom calendar name from registry.
internal string? CustomCalendar => Options.CustomCalendar;
/// Gets the trigger start delay in ms.
internal long TriggerStartDelay => Options.TriggerStartDelay;
///
public override IProducer CreateProducer()
{
throw new NotSupportedException("Cron endpoints do not support producers. Use them only as From() source.");
}
///
public override IConsumer CreateConsumer(IProcessor processor)
{
ArgumentNullException.ThrowIfNull(processor);
return new CronConsumer(this, processor);
}
}
///
/// Cron consumer. Fires the processor on a Quartz CronTrigger schedule.
///
public class CronConsumer : QuartzConsumerBase
{
private readonly CronEndpoint _endpoint;
/// Creates a cron consumer.
public CronConsumer(CronEndpoint endpoint, IProcessor processor)
: base(endpoint, processor, endpoint.Threads,
endpoint.GroupName, endpoint.JobName,
endpoint.DeleteJob, endpoint.PauseJob, endpoint.DurableJob,
endpoint.Stateful, endpoint.RecoverableJob,
endpoint.PrefixJobNameWithEndpointId, endpoint.CustomCalendar)
{
_endpoint = endpoint;
}
///
protected override ITrigger BuildTrigger(TriggerKey triggerKey, JobKey jobKey)
{
var builder = TriggerBuilder.Create()
.WithIdentity(triggerKey)
.ForJob(jobKey);
// Cron schedule with optional timezone and misfire
builder = builder.WithCronSchedule(_endpoint.Schedule, x =>
{
if (!string.IsNullOrEmpty(_endpoint.TimeZoneId))
x.InTimeZone(TimeZoneInfo.FindSystemTimeZoneById(_endpoint.TimeZoneId));
switch (_endpoint.MisfireInstruction)
{
case QuartzMisfirePolicy.CronDoNothing:
x.WithMisfireHandlingInstructionDoNothing();
break;
case QuartzMisfirePolicy.CronFireOnceNow:
x.WithMisfireHandlingInstructionFireAndProceed();
break;
// Default: use Quartz default
}
});
// Start date
if (!string.IsNullOrEmpty(_endpoint.StartAt))
builder = builder.StartAt(DateTimeOffset.Parse(_endpoint.StartAt, System.Globalization.CultureInfo.InvariantCulture));
else if (_endpoint.TriggerStartDelay > 0)
builder = builder.StartAt(DateTimeOffset.UtcNow.AddMilliseconds(_endpoint.TriggerStartDelay));
else
builder = builder.StartNow();
// End date
if (!string.IsNullOrEmpty(_endpoint.EndAt))
builder = builder.EndAt(DateTimeOffset.Parse(_endpoint.EndAt, System.Globalization.CultureInfo.InvariantCulture));
// Calendar exclusion
if (!string.IsNullOrEmpty(_endpoint.CustomCalendar))
builder = builder.ModifiedByCalendar(_endpoint.CustomCalendar);
return builder.Build();
}
///
protected override void PopulateExchangeProperties(IExchange exchange, IJobExecutionContext context)
{
exchange.Properties["CamelCronSchedule"] = _endpoint.Schedule;
exchange.Properties["CamelCronName"] = _endpoint.JobName;
exchange.Properties["CamelCronGroup"] = _endpoint.GroupName;
}
}