Path: redb-route/redb.Route.Quartz/QuartzTimerComponent.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/QuartzTimerComponent.cs
----
using Quartz;
using redb.Route.Abstractions;
using redb.Route.Core;
namespace redb.Route.Quartz;
///
/// Quartz-based timer component. Scheme: "qtimer".
/// Like the built-in "timer" but backed by Quartz.NET SimpleSchedule — supports
/// FixedRate mode, misfire handling, and shared scheduler.
/// URI: qtimer://group/name?period=1000&delay=0&fixedRate=true&threads=1
/// URI: qtimer://name?period=1000 (group defaults to "redb")
///
[EndpointRole(EndpointRole.Consumer, Hint = "Use it as a From() source.")]
public class QuartzTimerComponent : ComponentBase
{
///
public override string Scheme => "qtimer";
///
public override IEndpoint CreateEndpoint(EndpointUri uri)
{
ArgumentNullException.ThrowIfNull(uri);
var options = new QuartzTimerEndpointOptions();
options.BindFromUri(uri.RawParameters);
ParseGroupAndJob(uri.Path, options);
options.Validate();
return new QuartzTimerEndpoint(uri, this, options);
}
/// Parses "group/job" or "job" from the URI path into options.
internal static void ParseGroupAndJob(string path, QuartzTimerEndpointOptions 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"
}
}
}
///
/// Quartz timer endpoint options.
///
public class QuartzTimerEndpointOptions : EndpointOptions
{
/// Period between fires in milliseconds (default: 1000).
public int Period { get; set; } = 1000;
/// Initial delay before first fire in milliseconds (default: 0).
public int Delay { get; set; }
///
/// When true, fires at fixed rate regardless of processing time.
/// When false (default), next fire starts after previous completes + period.
///
public bool FixedRate { get; set; }
/// Maximum concurrent fires (default: 1).
public int Threads { get; set; } = 1;
// ── Group / Job (parsed from URI path: qtimer://group/job or qtimer://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;
/// Number of times to repeat. -1 = forever (default).
public int RepeatCount { get; set; } = -1;
/// Trigger start date (ISO 8601 format). If not set, uses Delay.
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; }
///
public override void Validate()
{
if (Period <= 0)
throw new ArgumentOutOfRangeException(nameof(Period), Period, "Period must be greater than 0.");
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.");
}
}
///
/// Quartz timer endpoint. Consumer-only — fires on a simple periodic schedule via Quartz.
///
public class QuartzTimerEndpoint : EndpointBase
{
/// Creates a Quartz timer endpoint.
public QuartzTimerEndpoint(EndpointUri uri, QuartzTimerComponent component, QuartzTimerEndpointOptions options)
: base(uri, component, options)
{
}
/// Gets the period in milliseconds.
internal int Period => Options.Period;
/// Gets the delay in milliseconds.
internal int Delay => Options.Delay;
/// Gets whether fixed-rate mode is enabled.
internal bool FixedRate => Options.FixedRate;
/// 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.
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 repeat count (-1 = forever).
internal int RepeatCount => Options.RepeatCount;
/// 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;
///
public override IProducer CreateProducer()
{
throw new NotSupportedException("QuartzTimer endpoints do not support producers. Use them only as From() source.");
}
///
public override IConsumer CreateConsumer(IProcessor processor)
{
ArgumentNullException.ThrowIfNull(processor);
return new QuartzTimerConsumer(this, processor);
}
}
///
/// Quartz timer consumer. Fires the processor on a Quartz SimpleSchedule.
/// Supports FixedRate mode, configurable delay, misfire policies, and all lifecycle options.
///
public class QuartzTimerConsumer : QuartzConsumerBase
{
private readonly QuartzTimerEndpoint _endpoint;
/// Creates a Quartz timer consumer.
public QuartzTimerConsumer(QuartzTimerEndpoint 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);
// Start date
if (!string.IsNullOrEmpty(_endpoint.StartAt))
builder = builder.StartAt(DateTimeOffset.Parse(_endpoint.StartAt, System.Globalization.CultureInfo.InvariantCulture));
else if (_endpoint.Delay > 0)
builder = builder.StartAt(DateTimeOffset.UtcNow.AddMilliseconds(_endpoint.Delay));
else
builder = builder.StartNow();
// End date
if (!string.IsNullOrEmpty(_endpoint.EndAt))
builder = builder.EndAt(DateTimeOffset.Parse(_endpoint.EndAt, System.Globalization.CultureInfo.InvariantCulture));
// SimpleSchedule with misfire handling
builder = builder.WithSimpleSchedule(x =>
{
x.WithInterval(TimeSpan.FromMilliseconds(_endpoint.Period));
if (_endpoint.RepeatCount < 0)
x.RepeatForever();
else
x.WithRepeatCount(_endpoint.RepeatCount);
// Misfire policy
switch (_endpoint.MisfireInstruction)
{
case QuartzMisfirePolicy.SimpleFireNow:
x.WithMisfireHandlingInstructionFireNow();
break;
case QuartzMisfirePolicy.SimpleRescheduleNowWithExistingRepeatCount:
x.WithMisfireHandlingInstructionNowWithExistingCount();
break;
case QuartzMisfirePolicy.SimpleRescheduleNowWithRemainingRepeatCount:
x.WithMisfireHandlingInstructionNowWithRemainingCount();
break;
case QuartzMisfirePolicy.SimpleRescheduleNextWithRemainingCount:
x.WithMisfireHandlingInstructionNextWithRemainingCount();
break;
case QuartzMisfirePolicy.SimpleRescheduleNextWithExistingCount:
x.WithMisfireHandlingInstructionNextWithExistingCount();
break;
default:
// Default: FixedRate → FireNow, otherwise → NextWithRemaining
if (_endpoint.FixedRate)
x.WithMisfireHandlingInstructionFireNow();
else
x.WithMisfireHandlingInstructionNextWithRemainingCount();
break;
}
});
// 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["CamelTimerName"] = _endpoint.JobName;
exchange.Properties["CamelTimerGroup"] = _endpoint.GroupName;
exchange.Properties["CamelTimerPeriod"] = _endpoint.Period;
exchange.Properties["CamelTimerFixedRate"] = _endpoint.FixedRate;
}
}