Bundle: redb-route / redb.Route.Quartz (redb.Route.Quartz.txt), 13 files Snapshot: 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 Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt ==== Path: redb-route/redb.Route.Quartz/AssemblyInfo.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/AssemblyInfo.cs ---- // redb_Route_Quartz - placeholder for build 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; } } Path: redb-route/redb.Route.Quartz/Extensions/ServiceCollectionExtensions.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/Extensions/ServiceCollectionExtensions.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Route.Extensions; namespace redb.Route.Quartz; /// /// Extension methods for registering Quartz scheduling components in a DI container. /// public static class ServiceCollectionExtensions { /// /// Registers both and /// in the route context so that cron:// and qtimer:// URIs are resolved. /// /// /// services.AddRedbRoute(route => /// { /// route.Services.AddRedbRouteQuartz(); /// route.AddRouteBuilder<MyRoutes>(); /// }); /// /// /// public static IServiceCollection AddRedbRouteQuartz(this IServiceCollection services) { services.AddSingleton(); services.AddSingleton(); // IRouteContextConfigurator is applied by RouteHostedService at startup -- // the correct registration hook (a lazy marker singleton never fires). services.AddRouteContextConfigurator((sp, context) => { context.AddComponent(sp.GetRequiredService()); context.AddComponent(sp.GetRequiredService()); }); return services; } /// /// Registers only the in the route context /// so that cron:// URIs are resolved. /// public static IServiceCollection AddRedbRouteCron(this IServiceCollection services) { services.AddRouteComponent(); return services; } /// /// Registers only the in the route context /// so that qtimer:// URIs are resolved. /// public static IServiceCollection AddRedbRouteQuartzTimer(this IServiceCollection services) { services.AddRouteComponent(); return services; } } Path: redb-route/redb.Route.Quartz/Fluent/Cron.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/Fluent/Cron.cs ---- using System.Text; using redb.Route.Abstractions; namespace redb.Route.Quartz; /// /// Fluent entry point for Cron consumer endpoints (Quartz-based). /// /// // Simple /// .From(Cron.Schedule("every5s", "0/5 * * * * ?")) /// /// // With group /// .From(Cron.Schedule("billing/invoice", "0 0 2 * * ?")) /// /// // Full options /// .From(Cron.Schedule("billing/invoice", "0 0 2 * * ?") /// .TimeZone("Europe/Moscow") /// .Stateful() /// .Recoverable() /// .MisfireInstruction(QuartzMisfirePolicy.CronDoNothing) /// .Threads(4)) /// /// public static class Cron { /// Create a cron-scheduled consumer. /// Logical job name, optionally "group/name" (default group: "redb"). /// Quartz cron expression (6-7 fields). public static CronBuilder Schedule(string name, string schedule) => new(name, schedule); } /// Fluent builder for Cron endpoint URIs. Scheme: cron. public sealed class CronBuilder { private readonly string _name; private readonly string _schedule; private string? _threads; // Job lifecycle private bool? _deleteJob; private bool? _pauseJob; private bool? _durableJob; private bool? _stateful; private bool? _recoverableJob; private bool? _prefixJobName; // Trigger timing private QuartzMisfirePolicy? _misfireInstruction; private string? _timeZone; private string? _startAt; private string? _endAt; private string? _customCalendar; private long? _triggerStartDelay; internal CronBuilder(string name, string schedule) { ArgumentException.ThrowIfNullOrWhiteSpace(name); ArgumentException.ThrowIfNullOrWhiteSpace(schedule); _name = name; _schedule = schedule; } /// Max concurrent fires. Default 1. public CronBuilder Threads(int count) { _threads = count.ToString(); return this; } /// Threads from an expression. public CronBuilder Threads(IExpression count) { _threads = count.ToTemplateString(); return this; } // ── Job lifecycle ── /// Delete the job when the route stops (default: true). public CronBuilder DeleteJob(bool value = true) { _deleteJob = value; return this; } /// Pause the trigger on route stop instead of deleting. public CronBuilder PauseJob(bool value = true) { _pauseJob = value; return this; } /// Keep the job even if no triggers reference it. public CronBuilder DurableJob(bool value = true) { _durableJob = value; return this; } /// PersistJobDataAfterExecution + DisallowConcurrentExecution. public CronBuilder Stateful(bool value = true) { _stateful = value; return this; } /// Re-execute the job on failover/recovery. public CronBuilder Recoverable(bool value = true) { _recoverableJob = value; return this; } /// Prefix the job name with the endpoint ID. public CronBuilder PrefixJobNameWithEndpointId(bool value = true) { _prefixJobName = value; return this; } // ── Trigger timing ── /// Misfire handling strategy. public CronBuilder MisfireInstruction(QuartzMisfirePolicy policy) { _misfireInstruction = policy; return this; } /// Time zone for the cron trigger (IANA ID, e.g. "Europe/Moscow"). public CronBuilder TimeZone(string tz) { _timeZone = tz; return this; } /// Trigger start date (ISO 8601). public CronBuilder StartAt(string date) { _startAt = date; return this; } /// Trigger start date. public CronBuilder StartAt(DateTimeOffset date) { _startAt = date.ToString("o"); return this; } /// Trigger end date (ISO 8601). public CronBuilder EndAt(string date) { _endAt = date; return this; } /// Trigger end date. public CronBuilder EndAt(DateTimeOffset date) { _endAt = date.ToString("o"); return this; } /// Reference to an ICalendar in the route context registry. public CronBuilder CustomCalendar(string calendarName) { _customCalendar = calendarName; return this; } /// Delay in ms before the first trigger fire (default: 500). public CronBuilder TriggerStartDelay(long ms) { _triggerStartDelay = ms; return this; } public string Build() { var sb = new StringBuilder(); sb.Append("cron:"); sb.Append(_name); sb.Append("?schedule="); sb.Append(Uri.EscapeDataString(_schedule)); void AppendIf(string key, string? v) { if (v != null) { sb.Append('&'); sb.Append(key); sb.Append('='); sb.Append(v); } } void AppendBool(string key, bool? v) { if (v.HasValue) { sb.Append('&'); sb.Append(key); sb.Append('='); sb.Append(v.Value ? "true" : "false"); } } AppendIf("threads", _threads); AppendBool("deleteJob", _deleteJob); AppendBool("pauseJob", _pauseJob); AppendBool("durableJob", _durableJob); AppendBool("stateful", _stateful); AppendBool("recoverableJob", _recoverableJob); AppendBool("prefixJobNameWithEndpointId", _prefixJobName); if (_misfireInstruction.HasValue) AppendIf("misfireInstruction", _misfireInstruction.Value.ToString()); AppendIf("timeZone", _timeZone); AppendIf("startAt", _startAt != null ? Uri.EscapeDataString(_startAt) : null); AppendIf("endAt", _endAt != null ? Uri.EscapeDataString(_endAt) : null); AppendIf("customCalendar", _customCalendar); if (_triggerStartDelay.HasValue) AppendIf("triggerStartDelay", _triggerStartDelay.Value.ToString()); return sb.ToString(); } public static implicit operator string(CronBuilder b) => b.Build(); public override string ToString() => Build(); } /// /// Fluent entry point for Quartz-based repeating timer. /// /// // Simple /// .From(QTimer.Every("heartbeat").Period(5000)) /// /// // With group /// .From(QTimer.Every("monitoring/heartbeat").Period(5000).FixedRate()) /// /// // Full options /// .From(QTimer.Every("monitoring/heartbeat") /// .Period(5000).Delay(1000).FixedRate() /// .Stateful() /// .Recoverable() /// .MisfireInstruction(QuartzMisfirePolicy.SimpleFireNow) /// .Threads(2)) /// /// public static class QTimer { /// Create a repeating timer consumer. /// Logical job name, optionally "group/name" (default group: "redb"). public static QTimerBuilder Every(string name) => new(name); } /// Fluent builder for Quartz Timer endpoint URIs. Scheme: qtimer. public sealed class QTimerBuilder { private readonly string _name; private string? _period; private string? _delay; private bool _fixedRate; private string? _threads; // Job lifecycle private bool? _deleteJob; private bool? _pauseJob; private bool? _durableJob; private bool? _stateful; private bool? _recoverableJob; private bool? _prefixJobName; // Trigger timing private QuartzMisfirePolicy? _misfireInstruction; private int? _repeatCount; private string? _startAt; private string? _endAt; private string? _customCalendar; internal QTimerBuilder(string name) { ArgumentException.ThrowIfNullOrWhiteSpace(name); _name = name; } /// Interval between fires in ms. Default 1000. public QTimerBuilder Period(int ms) { _period = ms.ToString(); return this; } /// Period from an expression. public QTimerBuilder Period(IExpression ms) { _period = ms.ToTemplateString(); return this; } /// Initial delay before first fire in ms. public QTimerBuilder Delay(int ms) { _delay = ms.ToString(); return this; } /// Delay from an expression. public QTimerBuilder Delay(IExpression ms) { _delay = ms.ToTemplateString(); return this; } /// Use fixed-rate scheduling instead of fixed-delay. public QTimerBuilder FixedRate() { _fixedRate = true; return this; } /// Max concurrent fires. Default 1. public QTimerBuilder Threads(int count) { _threads = count.ToString(); return this; } /// Threads from an expression. public QTimerBuilder Threads(IExpression count) { _threads = count.ToTemplateString(); return this; } // ── Job lifecycle ── /// Delete the job when the route stops (default: true). public QTimerBuilder DeleteJob(bool value = true) { _deleteJob = value; return this; } /// Pause the trigger on route stop instead of deleting. public QTimerBuilder PauseJob(bool value = true) { _pauseJob = value; return this; } /// Keep the job even if no triggers reference it. public QTimerBuilder DurableJob(bool value = true) { _durableJob = value; return this; } /// PersistJobDataAfterExecution + DisallowConcurrentExecution. public QTimerBuilder Stateful(bool value = true) { _stateful = value; return this; } /// Re-execute the job on failover/recovery. public QTimerBuilder Recoverable(bool value = true) { _recoverableJob = value; return this; } /// Prefix the job name with the endpoint ID. public QTimerBuilder PrefixJobNameWithEndpointId(bool value = true) { _prefixJobName = value; return this; } // ── Trigger timing ── /// Misfire handling strategy. public QTimerBuilder MisfireInstruction(QuartzMisfirePolicy policy) { _misfireInstruction = policy; return this; } /// Number of times to repeat. -1 = forever (default). public QTimerBuilder RepeatCount(int count) { _repeatCount = count; return this; } /// Trigger start date (ISO 8601). public QTimerBuilder StartAt(string date) { _startAt = date; return this; } /// Trigger start date. public QTimerBuilder StartAt(DateTimeOffset date) { _startAt = date.ToString("o"); return this; } /// Trigger end date (ISO 8601). public QTimerBuilder EndAt(string date) { _endAt = date; return this; } /// Trigger end date. public QTimerBuilder EndAt(DateTimeOffset date) { _endAt = date.ToString("o"); return this; } /// Reference to an ICalendar in the route context registry. public QTimerBuilder CustomCalendar(string calendarName) { _customCalendar = calendarName; return this; } public string Build() { var sb = new StringBuilder(); sb.Append("qtimer:"); sb.Append(_name); var sep = '?'; void AppendIf(string key, string? v) { if (v != null) { sb.Append(sep); sb.Append(key); sb.Append('='); sb.Append(v); sep = '&'; } } void AppendBool(string key, bool? v) { if (v.HasValue) { sb.Append(sep); sb.Append(key); sb.Append('='); sb.Append(v.Value ? "true" : "false"); sep = '&'; } } void AppendBoolFlag(string key, bool v) { if (v) { sb.Append(sep); sb.Append(key); sb.Append("=true"); sep = '&'; } } AppendIf("period", _period); AppendIf("delay", _delay); AppendBoolFlag("fixedRate", _fixedRate); AppendIf("threads", _threads); AppendBool("deleteJob", _deleteJob); AppendBool("pauseJob", _pauseJob); AppendBool("durableJob", _durableJob); AppendBool("stateful", _stateful); AppendBool("recoverableJob", _recoverableJob); AppendBool("prefixJobNameWithEndpointId", _prefixJobName); if (_misfireInstruction.HasValue) AppendIf("misfireInstruction", _misfireInstruction.Value.ToString()); if (_repeatCount.HasValue) AppendIf("repeatCount", _repeatCount.Value.ToString()); AppendIf("startAt", _startAt != null ? Uri.EscapeDataString(_startAt) : null); AppendIf("endAt", _endAt != null ? Uri.EscapeDataString(_endAt) : null); AppendIf("customCalendar", _customCalendar); return sb.ToString(); } public static implicit operator string(QTimerBuilder b) => b.Build(); public override string ToString() => Build(); } Path: redb-route/redb.Route.Quartz/QuartzConsumerBase.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/QuartzConsumerBase.cs ---- using System.Diagnostics; using Microsoft.Extensions.Logging; using Quartz; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Telemetry; namespace redb.Route.Quartz; /// /// Base class for Quartz-based consumers. Handles shared scheduler lifecycle, /// job creation, orphan cleanup, and concurrency control via semaphore. /// Subclasses provide trigger configuration (simple schedule vs cron expression). /// public abstract class QuartzConsumerBase : IConsumer { private readonly IEndpoint _endpoint; public IEndpoint Endpoint => _endpoint; private readonly IProcessor _processor; private readonly int _maxThreads; private readonly SemaphoreSlim _semaphore; private IScheduler? _scheduler; // Job/trigger identity private readonly string _groupName; private readonly string _jobName; // Job lifecycle private readonly bool _deleteJob; private readonly bool _pauseJob; private readonly bool _durableJob; private readonly bool _stateful; private readonly bool _recoverableJob; private readonly bool _prefixJobNameWithEndpointId; private readonly string? _customCalendar; private CancellationTokenSource? _processingCts; private int _inflightCount; // Set by Start: the store is shared with the next start or the other nodes (it decides what Stop may touch), the // claim on the job key in the registry, and the context served (for a collision message). private bool _persistentStore; private string? _registryKey; private string? _contextId; /// /// How far ahead the replacement of a paused trigger starts, so it cannot fire before it is paused again. A trigger /// that stays paused loses nothing by it; one resumed within the margin fires first at its end. /// internal static readonly TimeSpan PausedReplaceMargin = TimeSpan.FromSeconds(10); /// Maximum time to wait for in-flight jobs to complete during stop. public TimeSpan DrainTimeout { get; set; } = TimeSpan.FromSeconds(30); /// Creates a Quartz consumer base. /// Owning endpoint. /// Downstream processor pipeline. /// Max concurrent job executions (default 1). /// Quartz group name (default "redb"). /// Quartz job/trigger name (default: endpoint path). /// Delete job on route stop (default true). /// Pause trigger on route stop (default false). /// Keep job without triggers (default false). /// PersistJobData + DisallowConcurrent (default false). /// Re-execute on failover (default false). /// Prefix job name with endpoint ID (default false). /// Calendar name from registry (default null). protected QuartzConsumerBase( IEndpoint endpoint, IProcessor processor, int maxThreads = 1, string? groupName = null, string? jobName = null, bool deleteJob = true, bool pauseJob = false, bool durableJob = false, bool stateful = false, bool recoverableJob = false, bool prefixJobNameWithEndpointId = false, string? customCalendar = null) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); _processor = processor ?? throw new ArgumentNullException(nameof(processor)); _maxThreads = maxThreads > 0 ? maxThreads : 1; _semaphore = new SemaphoreSlim(_maxThreads); _groupName = string.IsNullOrWhiteSpace(groupName) ? "redb" : groupName; _jobName = string.IsNullOrWhiteSpace(jobName) ? (endpoint.Uri?.Path ?? "default") : jobName; _deleteJob = deleteJob; _pauseJob = pauseJob; _durableJob = durableJob; _stateful = stateful; _recoverableJob = recoverableJob; _prefixJobNameWithEndpointId = prefixJobNameWithEndpointId; _customCalendar = customCalendar; } /// Gets the endpoint URI string used as job/trigger group key. protected string EndpointUriKey => _endpoint.Uri.NormalizedKey; /// /// Builds the Quartz trigger for this consumer. Called once during . /// /// Pre-built trigger key (name + group). /// The job key the trigger must reference. /// Configured trigger. protected abstract ITrigger BuildTrigger(TriggerKey triggerKey, JobKey jobKey); /// /// Populates exchange with component-specific properties (e.g. cron schedule, timer period, fire time). /// /// The exchange being built. /// Quartz job execution context with fire time info. protected abstract void PopulateExchangeProperties(IExchange exchange, IJobExecutionContext context); /// public async Task Start(CancellationToken ct = default) { _processingCts = new CancellationTokenSource(); Interlocked.Exchange(ref _inflightCount, 0); var routeContext = (_endpoint.Component as ComponentBase)?.Context; if (routeContext == null) throw new InvalidOperationException("Quartz consumer requires a RouteContext. Register the component via AddRedbRouteQuartz()."); var logger = (_endpoint.Component as ComponentBase)?.Logger; // The context's scheduler (handed in, or the context's own) — started once the context has started. var holder = QuartzContextScheduler.For(routeContext, logger); _scheduler = await holder.GetAsync(ct).ConfigureAwait(false); var metaData = await _scheduler.GetMetaData(ct).ConfigureAwait(false); _persistentStore = metaData.JobStoreSupportsPersistence; var effectiveJobName = _prefixJobNameWithEndpointId ? $"{EndpointUriKey}-{_jobName}" : _jobName; var jobKey = new JobKey(effectiveJobName, _groupName); // One job key, one consumer per scheduler — claimed before the scheduler is touched, so a second claimant // fails instead of replacing the first one's schedule (AddJob replace + RescheduleJob below). _registryKey = QuartzConsumerRegistry.KeyOf(_scheduler, jobKey); if (!QuartzConsumerRegistry.TryRegister(_registryKey, this, out var owner)) { _registryKey = null; throw new InvalidOperationException( $"Quartz job '{jobKey}' of {EndpointUri.Sanitize(EndpointUriKey)} (context '{routeContext.ContextId}') is " + $"already scheduled by {EndpointUri.Sanitize(owner.EndpointUriKey)} (context '{owner.ContextId}') on the " + $"same scheduler. One job key, one schedule: give it its own name (another path, or jobName=/groupName=)."); } try { WarnOnConfiguration(routeContext, metaData, logger); // Register custom calendar if specified if (!string.IsNullOrEmpty(_customCalendar)) { var calendar = routeContext.GetFromRegistry(_customCalendar); var existingCalendars = await _scheduler.GetCalendarNames(ct).ConfigureAwait(false); if (calendar != null && !existingCalendars.Contains(_customCalendar)) { await _scheduler.AddCalendar(_customCalendar, calendar, replace: true, updateTriggers: true, ct) .ConfigureAwait(false); } } var jobBuilder = _stateful ? JobBuilder.Create() : JobBuilder.Create(); var job = jobBuilder .WithIdentity(jobKey) .UsingJobData("endpointUri", EndpointUriKey) // For the log: the job is found by its key, not by the context id (another node writes its own). .UsingJobData("contextId", routeContext.ContextId) .UsingJobData("consumerType", GetType().AssemblyQualifiedName) .StoreDurably(_durableJob) .RequestRecovery(_recoverableJob) .Build(); await _scheduler.AddJob(job, replace: true, storeNonDurableWhileAwaitingScheduling: true, ct).ConfigureAwait(false); // Build trigger from subclass var triggerKey = new TriggerKey(effectiveJobName, _groupName); var trigger = BuildTrigger(triggerKey, jobKey); // An operator's pause (a host's panel, CLI or API) stays. On a persistent store the route never pauses, so a // paused trigger there is the operator's; so it is on an in-memory store without pauseJob=true. Where the // in-memory stop paused (pauseJob=true) or removed (deleteJob=true) the job itself, its note on the // scheduler tells whether the operator had paused it: taken here, it lives from one stop to the next start. var notedPause = !_persistentStore && TakeOperatorPause(_scheduler, jobKey); var exists = await _scheduler.CheckExists(triggerKey, ct).ConfigureAwait(false); var held = exists ? await _scheduler.GetTriggerState(triggerKey, ct).ConfigureAwait(false) == TriggerState.Paused && (_persistentStore || !_pauseJob || notedPause) : notedPause; if (held) { // A trigger is stored as waiting: the held one starts after a margin and is paused again within it, so // nothing fires between the two calls, on this node or another of the cluster. var holdUntil = DateTimeOffset.UtcNow + PausedReplaceMargin; if (trigger.StartTimeUtc < holdUntil && (trigger.EndTimeUtc is null || trigger.EndTimeUtc > holdUntil)) trigger = trigger.GetTriggerBuilder().StartAt(holdUntil).Build(); } if (exists) await _scheduler.RescheduleJob(triggerKey, trigger, ct).ConfigureAwait(false); else await _scheduler.ScheduleJob(trigger, ct).ConfigureAwait(false); if (held) { await _scheduler.PauseTrigger(triggerKey, ct).ConfigureAwait(false); logger?.LogInformation("{Endpoint}: Quartz job '{Job}' was paused on the scheduler and stays paused; " + "resume it there to fire it again.", EndpointUri.Sanitize(EndpointUriKey), jobKey); } _contextId = routeContext.ContextId; // A route started in a running context starts the scheduler itself; otherwise the context's start does. await holder.StartIfContextRunningAsync(ct).ConfigureAwait(false); } catch { QuartzConsumerRegistry.Unregister(_registryKey, this); _registryKey = null; throw; } } /// public async Task Stop(CancellationToken ct = default) { // Unregister first: a fire from now on finds no consumer on this node if (_registryKey is not null) { QuartzConsumerRegistry.Unregister(_registryKey, this); _registryKey = null; } if (_scheduler == null || _scheduler.IsShutdown) return; var effectiveJobName = _prefixJobNameWithEndpointId ? $"{EndpointUriKey}-{_jobName}" : _jobName; var triggerKey = new TriggerKey(effectiveJobName, _groupName); var jobKey = new JobKey(effectiveJobName, _groupName); // A trigger paused before this stop touches it is the operator's: noted on the scheduler for the next start of // the route, before the pause or removal below hides it. if (!_persistentStore && (_pauseJob || _deleteJob) && await _scheduler.CheckExists(triggerKey, ct).ConfigureAwait(false) && await _scheduler.GetTriggerState(triggerKey, ct).ConfigureAwait(false) == TriggerState.Paused) { NoteOperatorPause(_scheduler, jobKey); } if (_persistentStore) { // The job and its trigger live in a store the next start of this node, or the other nodes of a cluster, // share: this node stopping its consumer is not a decision about the schedule. deleteJob / pauseJob apply to // an in-memory store only; a schedule is paused or removed for the cluster explicitly. } else if (_pauseJob) { // Pause instead of delete — trigger stays in scheduler for reuse if (await _scheduler.CheckExists(triggerKey, ct).ConfigureAwait(false)) { await _scheduler.PauseTrigger(triggerKey, ct).ConfigureAwait(false); } } else if (_deleteJob) { // Unschedule trigger if (await _scheduler.CheckExists(triggerKey, ct).ConfigureAwait(false)) { await _scheduler.UnscheduleJob(triggerKey, ct).ConfigureAwait(false); } // Delete job only if no more triggers reference it and not durable if (!_durableJob && await _scheduler.CheckExists(jobKey, ct).ConfigureAwait(false)) { var triggers = await _scheduler.GetTriggersOfJob(jobKey, ct).ConfigureAwait(false); if (triggers.Count == 0) { await _scheduler.DeleteJob(jobKey, ct).ConfigureAwait(false); } } } // Drain in-flight jobs var logger = (_endpoint.Component as ComponentBase)?.Logger; await DrainAwaiter.WaitAsync( () => Volatile.Read(ref _inflightCount), DrainTimeout, ct, logger, GetType().Name).ConfigureAwait(false); // Cancel any still-running processing _processingCts?.Cancel(); _processingCts?.Dispose(); _processingCts = null; } /// Context id of the route this consumer serves, for the collision message of another claimant. internal string? ContextId => _contextId; private void WarnOnConfiguration(IRouteContext routeContext, SchedulerMetaData metaData, ILogger? logger) { if (logger is null) return; if (metaData.JobStoreSupportsPersistence && (_endpoint.Uri.RawParameters.ContainsKey("deleteJob") || _endpoint.Uri.RawParameters.ContainsKey("pauseJob"))) { logger.LogWarning("{Endpoint}: deleteJob / pauseJob do not apply to a persistent job store — stopping a route on one node does " + "not delete or pause the schedule the store shares. Pause or remove it explicitly.", EndpointUri.Sanitize(EndpointUriKey)); } // A clustered store already fires a job on one node of the cluster; a leader-only route policy on top keeps the // consumer on the leader alone, and a fire taken by another node finds no consumer there and is lost. A policy // factory that declines the route (Tsak's does for Quartz routes) leaves it on every node: nothing to warn about. if (metaData.JobStoreClustered && routeContext.Routes.FirstOrDefault(r => ReferenceEquals(r.Consumer, this)) is { PolicyDescriptor: { RequestedCluster: true, EffectivePolicy: not "AllNodes" } } route) { logger.LogWarning("Route '{RouteId}': .Cluster(true) on a Quartz consumer with a clustered job store — Quartz already fires " + "the job on one node; with the route on the leader only, a fire taken by another node is lost. Drop .Cluster(true).", route.RouteId); } } /// /// Executes the consumer pipeline for a job fire. Called by . /// /// Quartz job execution context. internal async Task ExecuteJob(IJobExecutionContext jobContext) { var processingCt = _processingCts?.Token ?? CancellationToken.None; if (processingCt.IsCancellationRequested) return; // stop accepted, reject new jobs if (!await _semaphore.WaitAsync(0).ConfigureAwait(false)) return; // all threads busy, skip this fire Interlocked.Increment(ref _inflightCount); try { var exchange = CreateExchange(jobContext); // A fire carries no trace context: its span is a root, never a child of the scheduler thread's activity. using var span = RouteTelemetryExtensions.StartConsumerSpan( (_endpoint.Component as ComponentBase)?.Context, $"{_endpoint.Component.Scheme} receive", ActivityKind.Consumer, "redb.system", _endpoint.Component.Scheme, _endpoint.Uri.NormalizedKey, null, static (_, _) => null, operation: "receive"); try { await _processor.Process(exchange, processingCt).ConfigureAwait(false); // The route's error scope has run inside the pipeline — its OnException blocks, its builder's, and the // context's handlers (a host's dead letter queue among them) for a failure none took. A failure left on // the exchange is the outcome of the fire: recorded, not handled again. As DrainableConsumer. // Our own stop is not a failure of the fire; any other cancellation is. if (exchange.Exception != null && !exchange.ExceptionHandled && (exchange.Exception is not OperationCanceledException || !processingCt.IsCancellationRequested)) span.Activity.RecordFailure(exchange.Exception); } catch (Exception ex) when (ex is not OperationCanceledException || !processingCt.IsCancellationRequested) { span.Activity.RecordFailure(ex); throw; } finally { await exchange.DisposeAsync().ConfigureAwait(false); } } finally { _semaphore.Release(); Interlocked.Decrement(ref _inflightCount); } } private Exchange CreateExchange(IJobExecutionContext context) { var message = new Message { Body = null }; var exchange = Exchange.Create(message, _endpoint.ScopeFactory); exchange.Pattern = ExchangePattern.InOnly; exchange.Properties["CamelQuartzFireTime"] = context.FireTimeUtc; exchange.Properties["CamelQuartzScheduledFireTime"] = context.ScheduledFireTimeUtc; exchange.Properties["CamelQuartzNextFireTime"] = context.NextFireTimeUtc; exchange.Properties["CamelQuartzPreviousFireTime"] = context.PreviousFireTimeUtc; PopulateExchangeProperties(exchange, context); return exchange; } private const string OperatorPausePrefix = "redb.route.quartz.operator-paused:"; /// /// Notes on that the operator had paused when its route /// stopped. Kept in the scheduler's own context, so it lives exactly as long as an in-memory store does: across a /// restart of the route or a new context on a host's scheduler, gone with the scheduler. /// private static void NoteOperatorPause(IScheduler scheduler, JobKey jobKey) { lock (scheduler.Context) scheduler.Context.Put(OperatorPausePrefix + jobKey, true); } /// Takes the note of : whether it was there. private static bool TakeOperatorPause(IScheduler scheduler, JobKey jobKey) { lock (scheduler.Context) return scheduler.Context.Remove(OperatorPausePrefix + jobKey); } /// /// Removes orphaned job/trigger from scheduler when the endpoint is no longer present. /// internal static async Task CleanupOrphanedJob(IScheduler scheduler, JobKey jobKey, TriggerKey triggerKey, CancellationToken ct = default) { if (await scheduler.CheckExists(triggerKey, ct).ConfigureAwait(false)) { await scheduler.UnscheduleJob(triggerKey, ct).ConfigureAwait(false); } if (await scheduler.CheckExists(jobKey, ct).ConfigureAwait(false)) { var triggers = await scheduler.GetTriggersOfJob(jobKey, ct).ConfigureAwait(false); if (triggers.Count == 0) { await scheduler.DeleteJob(jobKey, ct).ConfigureAwait(false); } } } } Path: redb-route/redb.Route.Quartz/QuartzConsumerRegistry.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/QuartzConsumerRegistry.cs ---- using System.Collections.Concurrent; using Quartz; namespace redb.Route.Quartz; /// /// The running Quartz consumers of this process, by the job they claimed on their scheduler — the key Quartz fires by. /// One job key, one consumer per scheduler: refuses a second claimant, so two routes never /// share (and silently replace) one schedule. The same key on another node of a cluster is not a claimant here — /// it is that node's own consumer of the same schedule. /// internal static class QuartzConsumerRegistry { private static readonly ConcurrentDictionary Consumers = new(StringComparer.Ordinal); /// The registry key of on (this process's instance of it). internal static string KeyOf(IScheduler scheduler, JobKey jobKey) => $"{scheduler.SchedulerName}|{scheduler.SchedulerInstanceId}|{jobKey.Group}|{jobKey.Name}"; /// Claims for ; false with the current owner when taken. internal static bool TryRegister(string key, QuartzConsumerBase consumer, out QuartzConsumerBase owner) { owner = Consumers.GetOrAdd(key, consumer); return ReferenceEquals(owner, consumer); } /// Releases if holds it. internal static void Unregister(string key, QuartzConsumerBase consumer) => Consumers.TryRemove(new KeyValuePair(key, consumer)); /// The consumer that claimed on , or null. internal static QuartzConsumerBase? Get(IScheduler scheduler, JobKey jobKey) => Consumers.TryGetValue(KeyOf(scheduler, jobKey), out var consumer) ? consumer : null; } Path: redb-route/redb.Route.Quartz/QuartzContextScheduler.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/QuartzContextScheduler.cs ---- using System.Collections.Specialized; using Microsoft.Extensions.Logging; using Quartz; using Quartz.Impl; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Extensions; namespace redb.Route.Quartz; /// /// The scheduler of one route context, as Apache Camel's QuartzComponent keeps one per CamelContext. A service of /// the context, created by its first Quartz consumer: /// /// an IScheduler handed to the context is used as it is — its host owns it; /// otherwise the context gets its own, built from (in-memory without them), /// named {prefix}-{context id}, and shut down when the context stops; /// either is started once the context has started — every consumer registered before the first fire (camel-quartz /// autoStartScheduler) — or at once for a consumer started later in a running context. /// /// internal sealed class QuartzContextScheduler : IRouteLifecycleListener { private static readonly object HolderLock = new(); private readonly IRouteContext _context; private readonly ILogger? _logger; private readonly SemaphoreSlim _lock = new(1, 1); private IScheduler? _scheduler; private bool _owned; private QuartzContextScheduler(IRouteContext context, ILogger? logger) { _context = context; _logger = logger; } /// The scheduler holder of , created and registered on first use. internal static QuartzContextScheduler For(IRouteContext context, ILogger? logger) { lock (HolderLock) { if (context.GetService() is { } existing) return existing; var holder = new QuartzContextScheduler(context, logger); context.AddService(typeof(QuartzContextScheduler), holder); context.AddLifecycleListener(holder); return holder; } } /// /// The context's scheduler, not started by this call. A handed-in one that has been shut down is refused; the /// context's own is built anew after the context stopped it. /// internal async Task GetAsync(CancellationToken ct) { var scheduler = await ResolveAsync(ct).ConfigureAwait(false); // The job Quartz instantiates has no container to take a logger from: it finds one here. if (_logger is not null) scheduler.Context.Put(QuartzRouteJob.LoggerKey, _logger); return scheduler; } private async Task ResolveAsync(CancellationToken ct) { await _lock.WaitAsync(ct).ConfigureAwait(false); try { if (_scheduler is { IsShutdown: false }) return _scheduler; // A handed-in scheduler is any IScheduler of the context that is not the one built here (that one stays // registered after the context shut it down, and is built anew below). if (_context.GetService() is { } handedIn && !ReferenceEquals(handedIn, _scheduler)) { if (handedIn.IsShutdown) throw new InvalidOperationException("The Quartz scheduler handed to the route context has been shut down."); _scheduler = handedIn; _owned = false; return handedIn; } _scheduler = await CreateOwnAsync(ct).ConfigureAwait(false); _owned = true; // Visible as the context's IScheduler, as it always was; the holder still knows it is its own. _context.AddService(typeof(IScheduler), _scheduler); return _scheduler; } finally { _lock.Release(); } } /// Whether the context owns its scheduler (built here) rather than a host. internal bool Owned => _owned; /// Starts the scheduler when the context is already running — a consumer started after the context. internal Task StartIfContextRunningAsync(CancellationToken ct) => _context.IsStarted ? StartAsync(ct) : Task.CompletedTask; /// public Task OnContextStarted(IRouteContext context, CancellationToken ct) => StartAsync(ct); /// public async Task OnContextStopped(IRouteContext context, CancellationToken ct) { await _lock.WaitAsync(ct).ConfigureAwait(false); try { // The consumers have stopped and drained; the context's own scheduler goes with the context. A handed-in // one belongs to its host. if (_owned && _scheduler is { IsShutdown: false } own) { await own.Shutdown(waitForJobsToComplete: false, ct).ConfigureAwait(false); _logger?.LogDebug("Quartz scheduler {Scheduler} of context {Context} shut down.", own.SchedulerName, context.ContextId); } } finally { _lock.Release(); } } private async Task StartAsync(CancellationToken ct) { await _lock.WaitAsync(ct).ConfigureAwait(false); try { if (_scheduler is { IsStarted: false, IsShutdown: false } scheduler) await scheduler.Start(ct).ConfigureAwait(false); } finally { _lock.Release(); } } private async Task CreateOwnAsync(CancellationToken ct) { var options = _context.Resolve(); var properties = new NameValueCollection(); if (options is not null) { foreach (var (key, value) in options.Properties) properties[key] = value; } properties["quartz.scheduler.instanceName"] = $"{options?.InstanceNamePrefix ?? "redb-route"}-{_context.ContextId}"; var scheduler = await new StdSchedulerFactory(properties).GetScheduler(ct).ConfigureAwait(false); var metaData = await scheduler.GetMetaData(ct).ConfigureAwait(false); if (metaData.JobStoreSupportsPersistence && (_context as RouteContext)?.IsContextIdGenerated == true) { await scheduler.Shutdown(waitForJobsToComplete: false, ct).ConfigureAwait(false); throw new InvalidOperationException( $"The Quartz job store of context '{_context.ContextId}' is persistent, but the context id was generated: " + "the scheduler name would differ on every start and every node, and its jobs could not be found again. " + "Give the route context an id."); } return scheduler; } } Path: redb-route/redb.Route.Quartz/QuartzMisfirePolicy.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/QuartzMisfirePolicy.cs ---- namespace redb.Route.Quartz; /// /// Misfire handling strategies for Quartz triggers. /// Maps to Quartz.NET MisfireInstruction constants. /// public enum QuartzMisfirePolicy { /// Use the default misfire policy for the trigger type. Default = 0, // ── SimpleTrigger ── /// SimpleTrigger: fire now, then continue schedule. Default for simple triggers. SimpleFireNow = 1, /// SimpleTrigger: reschedule to now with the original repeat count. SimpleRescheduleNowWithExistingRepeatCount = 2, /// SimpleTrigger: reschedule to now with remaining repeat count. SimpleRescheduleNowWithRemainingRepeatCount = 3, /// SimpleTrigger: reschedule to next scheduled time with remaining count. SimpleRescheduleNextWithRemainingCount = 4, /// SimpleTrigger: reschedule to next scheduled time with existing count. SimpleRescheduleNextWithExistingCount = 5, // ── CronTrigger ── /// CronTrigger: fire once now, then continue schedule. Default for cron triggers. CronFireOnceNow = 101, /// CronTrigger: do nothing, wait for next scheduled time. CronDoNothing = 102, } Path: redb-route/redb.Route.Quartz/QuartzRouteJob.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/QuartzRouteJob.cs ---- using System.Collections.Concurrent; using Microsoft.Extensions.Logging; using Quartz; namespace redb.Route.Quartz; /// /// Universal Quartz job that bridges between Quartz scheduler and redb.Route consumers. /// Created via reflection by Quartz. Finds the running consumer by the job it claimed on this scheduler /// () and delegates execution. Concurrency is controlled by the consumer's /// semaphore, NOT by Quartz's [DisallowConcurrentExecution] — this allows configurable threads > 1. /// /// A fire with no consumer on this node: in an in-memory store the job is this process's own and is cleaned up; in a /// persistent store it belongs to the store — the next start of this node or another node of the cluster runs it (a /// rolling upgrade, a route stopped on one node) — so it is skipped and logged once, never deleted. /// /// public class QuartzRouteJob : IJob { /// Key of the logger the context's scheduler holder leaves in the scheduler context. internal const string LoggerKey = "redb.Route.Quartz.Logger"; private static readonly ConcurrentDictionary Warned = new(StringComparer.Ordinal); /// Parameterless constructor required by Quartz reflection-based instantiation. public QuartzRouteJob() { } /// public async Task Execute(IJobExecutionContext context) { var consumer = QuartzConsumerRegistry.Get(context.Scheduler, context.JobDetail.Key); if (consumer is not null) { // The consumer's semaphore + processor pipeline; the route's error scope runs inside it. await consumer.ExecuteJob(context).ConfigureAwait(false); return; } var metaData = await context.Scheduler.GetMetaData(context.CancellationToken).ConfigureAwait(false); if (!metaData.JobStoreSupportsPersistence) { // In-memory: the job is this process's own and its consumer is gone — clean up job + trigger. await QuartzConsumerBase.CleanupOrphanedJob( context.Scheduler, context.JobDetail.Key, context.Trigger.Key).ConfigureAwait(false); return; } if (Warned.TryAdd(QuartzConsumerRegistry.KeyOf(context.Scheduler, context.JobDetail.Key), 0) && context.Scheduler.Context.Get(LoggerKey) is ILogger logger) { logger.LogWarning( "Quartz job '{Job}' fired on node {Node} of scheduler {Scheduler}, which runs no consumer for it; the fire is " + "skipped and the job kept in the store. Nodes that share a scheduler name must carry the same schedules.", context.JobDetail.Key, context.Scheduler.SchedulerInstanceId, context.Scheduler.SchedulerName); } } } /// /// Stateful variant of . Persists JobDataMap after execution /// and disallows concurrent execution (single-threaded at Quartz scheduler level). /// Used when stateful=true is set on the endpoint. /// [DisallowConcurrentExecution] [PersistJobDataAfterExecution] public class QuartzStatefulRouteJob : QuartzRouteJob { } Path: redb-route/redb.Route.Quartz/QuartzSchedulerOptions.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/QuartzSchedulerOptions.cs ---- namespace redb.Route.Quartz; /// /// How the Quartz component builds the scheduler of a route context — the store, the cluster, the serializer, the /// thread pool — when nobody handed the context a ready IScheduler. Register it on the context /// (AddService) or in DI; the component then creates one scheduler per context, as Apache Camel's /// QuartzComponent does per CamelContext, named {InstanceNamePrefix}-{context id}. /// /// A host shares the options, not a scheduler: each context gets a job namespace of its own (two packages that both /// say cron://nightly do not collide), and in a clustered store a context's cluster is made of the nodes that /// run that context. A context without a cron:/qtimer: route creates no scheduler at all. /// /// public sealed class QuartzSchedulerOptions { /// Prefix of the scheduler name; the context id follows it. Default redb-route. public string InstanceNamePrefix { get; init; } = "redb-route"; /// /// Quartz properties of the scheduler (quartz.jobStore.type, quartz.jobStore.clustered, /// quartz.dataSource.*, quartz.serializer.type, quartz.threadPool.maxConcurrency...). /// quartz.scheduler.instanceName is set by the component. /// public IReadOnlyDictionary Properties { get; init; } = new Dictionary(); } 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; } } Path: redb-route/redb.Route.Quartz/README.md 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/README.md ---- # redb.Route.Quartz > Documentation and articles: Quartz.NET scheduling transport for redb.Route. Cron-expression schedules and interval timers backed by the Quartz scheduler with thread pool management. [![NuGet](https://img.shields.io/nuget/v/redb.Route.Quartz?label=NuGet&color=blue)](https://www.nuget.org/packages/redb.Route.Quartz) [![License: Apache 2.0](https://img.shields.io/badge/license-Apache%202.0-blue)](../../LICENSE) ## Installation ```bash dotnet add package redb.Route.Quartz ``` ## Usage ### Fluent DSL ```csharp using redb.Route.Quartz; // Cron schedule — every weekday at 8:00 AM From(Cron.Schedule("daily-report", "0 0 8 ? * MON-FRI")) .Log("Running daily report") .To("direct://generate-report"); // Cron with thread pool From(Cron.Schedule("batch-job", "0 */15 * * * ?").Threads(4)) .To("direct://batch-process"); // Interval timer — every 5 seconds From(QTimer.Every("heartbeat").Period(5000).Delay(1000)) .SetBody(_ => new { status = "alive", time = DateTime.UtcNow }) .To("direct://monitor"); // Fixed-rate timer From(QTimer.Every("metrics").Period(10000).FixedRate().Threads(2)) .To("direct://collect-metrics"); ``` ## Fluent Builder API | Category | Methods | |----------|---------| | **Cron** | `Cron.Schedule(name, expression)`, `.Threads(int)` | | **Timer** | `QTimer.Every(name)`, `.Period(ms)`, `.Delay(ms)`, `.FixedRate()`, `.Threads(int)` | ## Two Schemes | Scheme | Component | Description | |--------|-----------|-------------| | `cron` | `CronComponent` | Cron expression scheduling (e.g., `0 0 8 ? * MON-FRI`) | | `qtimer` | `QuartzTimerComponent` | Interval-based timer with optional initial delay | Both schemes are consumer-only — they generate messages on schedule. > Builder methods (Threads, Period, Delay) accept both constant values and `IExpression` for runtime resolution via the expression engine. ## The scheduler of a context As Apache Camel's `QuartzComponent`, each route context has one scheduler, created by its first `cron:`/`qtimer:` consumer — a context without such a route creates none: - an `IScheduler` handed to the context (`context.AddService(typeof(IScheduler), scheduler)`) is used as it is; its host owns it; - otherwise the context builds its own, from `QuartzSchedulerOptions` when the context or DI has them (store, cluster, serializer, thread pool), in memory without them, named `{InstanceNamePrefix}-{context id}`, and shuts it down when the context stops. Either is started once the context has started — every consumer registered before the first fire (camel-quartz `autoStartScheduler`); a route started later in a running context starts it at once. ```csharp // A host shares the options, not a scheduler: every context gets its own, its own job namespace and, in a clustered // store, a cluster of the nodes that run that context. context.AddService(typeof(QuartzSchedulerOptions), new QuartzSchedulerOptions { InstanceNamePrefix = "MyCluster", Properties = new Dictionary { ["quartz.jobStore.type"] = "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz", ["quartz.jobStore.clustered"] = "true", // dataSource, driverDelegateType, serializer, threadPool... }, }); ``` A persistent store keys the scheduler by the context id, so the context needs a given id (`new RouteContext("billing")`): with a generated one the scheduler name would differ on every start and every node, and starting fails with a message. ## One job, one consumer The job key is `{groupName}.{jobName}` — `redb` and the endpoint path by default (`cron://nightly` → `redb.nightly`). It depends on the URI only, so it is the same after a restart and on every node of a cluster. On one scheduler a job key has one consumer: a second claimant — the same path with another schedule, `cron://nightly` beside `qtimer://nightly`, two contexts deliberately sharing one scheduler — fails at its start, naming both endpoints, instead of silently replacing the first one's schedule. Give it its own name: another path, or `jobName=` / `groupName=`. ## A job paused on the scheduler A job paused on the scheduler (a host's panel, CLI or API) stays paused when its route starts again, on any store: the start applies the route's schedule to it and keeps the pause, and logs so. Resume it on the scheduler to fire it again; resumed within ten seconds of the start, it fires first at their end. On an in-memory store the stop removes the job (`deleteJob=true`, the default) or pauses it (`pauseJob=true`). A pause found at the stop is noted on the scheduler, and the next start of the route pauses the job again; the route's own `pauseJob` pause is lifted at its start. A job resumed while its route was stopped starts unpaused. The note lives with the scheduler: a job whose route never starts again keeps it until the scheduler shuts down, and another route that later takes the same job key on that scheduler starts paused (logged). ## A persistent or clustered store The store is shared — with this node's next start, or with the other nodes of a cluster — so a node never decides about the schedule by itself: - stopping a route stops this node's consumer only; `deleteJob` / `pauseJob` apply to an in-memory store (a warning when set on a persistent one); pause or remove a schedule for the cluster explicitly; - a fire taken by a node that runs no consumer for it — a rolling upgrade, a route stopped on one node — is skipped and logged once; the job stays in the store (in memory it is cleaned up, it was the process's own); - nodes that share a scheduler name must carry the same schedules: separate roles get separate names. With a scheduler per context the cluster of a context is made of the nodes that run it; - `.Cluster(true)` on a Quartz route over a clustered store is a warning when a leader-only policy is attached: Quartz already fires a job on one node, and a leader-only route loses the fires the other nodes take. A host may decline the policy for Quartz routes (redb.Tsak does); the route then runs on every node. ## Part of [redb.Route](../README.md) — ESB & EIP Framework for .NET ## Tracing On the `redb.Route` activity source (`AddSource("redb.Route")`), with `redb.system` = the scheme (`cron`, `qtimer`) and `redb.route.endpoint`: one `Consumer` span per fire, `{scheme} receive`. A fire carries no trace context, so the span is a root, never a child of the activity the scheduler thread holds; the route is its child. A failed route marks it an error; our own stop does not. `RouteEngineOptions.EnableTelemetry = false` opens none. Path: redb-route/redb.Route.Quartz/redb.Route.Quartz.csproj 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/redb.Route.Quartz.csproj ---- redb.Route.Quartz Quartz.NET scheduling transport for redb.Route ESB framework. Provides Cron and QuartzTimer components. esb;messaging;quartz;cron;timer;scheduling;redb README.md