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