Quartz.NETQuartz.NET
Home
Features
Discussions
NuGet
GitHub
Home
Features
Discussions
NuGet
GitHub
  • Getting Started

    • Quartz 3 Quick Start
    • Tutorial
      • Using Quartz
      • Library Overview
      • Jobs And Triggers
      • More About Jobs
      • More About Triggers
      • Execution Groups
      • Node Affinity (Preferred Node)
      • Simple Triggers
      • Cron Triggers
      • RecurrenceTrigger
      • Trigger and Job Listeners
      • Scheduler Listeners
      • Job Stores
      • Tuning the Scheduler
      • Configuration, Resource Usage and SchedulerFactory
      • Advanced (Enterprise) Features
    • Configuration Reference
    • JSON Configuration
    • Multi-Tenancy
    • Frequently Asked Questions
    • Best Practices
    • Tenancy Patterns
    • Troubleshooting
    • API Documentation
    • Database Schema
    • Database Schema Changes
    • Migration Guide
    • Miscellaneous Features
  • How To's

    • One-Off Job
    • Multiple Triggers
    • Job Template
    • Using the CronTrigger
    • Rescheduling Jobs
  • Packages

    • Quartz Core Additions

      • Dashboard
      • Jobs
      • Serialization (System.Text.Json)
      • Serialization (Newtonsoft Json.NET)
      • Plugins
    • Integrations

      • ASP.NET Core Integration
      • Hosted Services Integration
      • Microsoft DI Integration
      • Multiple Schedulers with Microsoft DI
      • OpenTelemetry Integration
      • OpenTracing Integration
      • Redis Lock Handler
      • TimeZoneConverter Integration
    • 3rd Party Plugins for Quartz
  • Unreleased Releases

    • Quartz 4.x
      • Quartz 4 Quick Start
      • Tutorial
        • Using Quartz
        • Jobs And Triggers
        • More About Jobs & JobDetails
        • Job Data
        • More About Triggers
        • Querying Jobs and Triggers
        • Simple Triggers
        • Cron Triggers
        • RecurrenceTrigger
        • Time and TimeProvider
        • Trigger and Job Listeners
        • Scheduler Listeners
        • Job Execution Middleware
        • Job Stores
        • Configuration, Resource Usage and Building a Scheduler
        • Building a Scheduler Without a Host
        • Clustering
        • Execution Groups
        • Node Affinity (Preferred Node)
        • Testing
      • Configuration Reference
      • JSON Configuration
      • Cron Expression Reference
      • Multi-Tenancy
      • Frequently Asked Questions
      • Best Practices
      • Operating a Cluster
      • Tenancy Patterns
      • Database Schema
      • Database Schema Changes
      • Migration Guide
      • Troubleshooting
      • API Documentation
      • How To's
        • One-Off Job
        • Rescheduling Jobs
        • Retrying Failed Jobs
        • Multiple Triggers
        • Job Template
        • Running Quartz under Aspire
        • Quartz.NET with Wolverine
        • Embedding Quartz in a Library
        • Running under an External Leader Election
        • Publishing Trimmed and Native AOT
        • A Job Store of Your Own
        • A Driver Delegate for a New Database
        • Persisting a Custom Trigger Type
        • A Lock Handler of Your Own
      • Packages

        • Quartz Core Additions

          • Jobs
          • Serialization (System.Text.Json)
          • JSON Serialization
          • Plugins
        • Integrations

          • Aspire Integration
          • ASP.NET Core Integration
          • HTTP API
          • HTTP Client
          • Dashboard
          • Hosted Services Integration
          • Microsoft DI Integration
          • Multiple Schedulers with Microsoft DI
          • Observability
          • Redis Lock Handler
          • TimeZoneConverter Integration
        • 3rd Party Plugins for Quartz
  • Old Releases

    • Quartz 2.x
      • Quartz 2 Quick Start
      • Tutorial
        • Lesson 1: Using Quartz
        • Lesson 2: Jobs And Triggers
        • Lesson 3: More About Jobs & JobDetails
        • Lesson 4: More About Triggers
        • Lesson 5: SimpleTrigger
        • Lesson 6: CronTrigger
        • Lesson 7: TriggerListeners and JobListeners
        • Lesson 8: SchedulerListeners
        • Lesson 9: JobStores
        • Lesson 10: Configuration, Resource Usage and SchedulerFactory
        • Lesson 11: Advanced (Enterprise) Features
        • Lesson 12: Miscellaneous Features of Quartz
        • CronTrigger Tutorial
      • Configuration Reference
      • Migration Guide
      • API Documentation
    • Quartz 1.x
      • Tutorial
        • Lesson 1: Using Quartz
        • Lesson 2: Jobs And Triggers
        • Lesson 3: More About Jobs & JobDetails
        • Lesson 4: More About Triggers
        • Lesson 5: SimpleTrigger
        • Lesson 6: CronTrigger
        • Lesson 7: TriggerListeners and JobListeners
        • Lesson 8: SchedulerListeners
        • Lesson 9: JobStores
        • Lesson 10: Configuration, Resource Usage and SchedulerFactory
        • Lesson 11: Advanced (Enterprise) Features
        • Lesson 12: Miscellaneous Features of Quartz
      • API Documentation
  • License

Job Execution Middleware

Middleware wraps every job a scheduler executes. It is where a cross-cutting concern lives — a log scope, a tenant context, a metric, a translation of what a third-party library throws — when that concern has to surround the call to the job rather than merely hear about it.

Listeners cannot do this. An IJobListener is notified before the job runs and again after it has run, but the execution happens between the two notifications rather than inside them, so a listener cannot open an await using around it, cannot decline to run it, and cannot catch what it threw. Before 4.0 the only place left for such code was a job that wrapped another job, which is why several frameworks built on Quartz ship exactly that adapter.

The interface

public delegate ValueTask JobExecutionDelegate(IJobExecutionContext context, CancellationToken cancellationToken);

public interface IJobExecutionMiddleware
{
    ValueTask Invoke(IJobExecutionContext context, JobExecutionDelegate next, CancellationToken cancellationToken = default);
}

next is the rest of the chain, ending in the job. Await it to run the job; do not, and the job does not run.

Writing one

public sealed class LogScopeMiddleware(ILogger<LogScopeMiddleware> logger) : IJobExecutionMiddleware
{
    public async ValueTask Invoke(IJobExecutionContext context, JobExecutionDelegate next, CancellationToken cancellationToken = default)
    {
        using IDisposable? scope = logger.BeginScope(new Dictionary<string, object>
        {
            ["JobKey"] = context.JobDetail.Key,
            ["FireInstanceId"] = context.FireInstanceId,
        });

        await next(context, cancellationToken);
    }
}

Registering

Middleware belongs to a scheduler, so it is registered where the scheduler is configured. The same three shapes listeners have: the container builds it, you build it from the container, or you hand over one you already have.

builder.AddQuartz(q =>
{
    // built by the container, so it can take dependencies of its own
    q.AddJobMiddleware<LogScopeMiddleware>();

    // built by you, from this scheduler's services
    q.AddJobMiddleware(provider => new MeteredMiddleware(provider.GetRequiredService<IMeterFactory>()));

    // one you already have
    q.AddJobMiddleware(new TenantScopeMiddleware());
});

The standalone builder takes the same calls, because it is an IQuartzBuilder:

IScheduler scheduler = await QuartzSchedulerBuilder.Create()
    .UseInMemoryStore()
    .AddJobMiddleware<LogScopeMiddleware>()
    .BuildScheduler();

Tips

Registering a middleware for AddQuartz("reporting", …) puts it in that scheduler's pipeline alone. A named scheduler's middleware is its own, the way its listeners and its job store are.

Order

Middleware runs in registration order, outermost first. The first registered sees the firing before the second does and sees its result after it, which is the ordering a log scope or a transaction has to be planned around:

q.AddJobMiddleware<A>();     A ─┐
q.AddJobMiddleware<B>();        B ─┐
                                   job
                                B ─┘
                             A ─┘

Each call adds a stage, so registering the same type twice puts it in the chain twice.

The chain is composed once, when the scheduler is built, and one instance of each middleware serves every firing that scheduler performs. A middleware must therefore keep no per-firing state in a field — see Per-firing state below.

Where it runs

after the trigger and job listeners have been notifieda fire a listener vetoed never reaches the pipeline
inside the execution span and the duration measurementwhat a middleware costs is part of what the firing cost, and anything it traces is a child of Quartz.Job.Execute
outside the run shell's exception handlingwhat a middleware throws is classified exactly as though the job had thrown it
inside the store's concurrency handling[DisallowConcurrentExecution] is enforced above the pipeline, so a middleware never sees two firings of one job overlapping

Short-circuiting

A middleware that does not call next keeps the call to itself. The job does not run; everything else about the firing is unchanged — the listeners are notified as usual, and the trigger is left where a successful execution leaves it.

public sealed class FeatureFlagMiddleware(FeatureFlags flags) : IJobExecutionMiddleware
{
    public ValueTask Invoke(IJobExecutionContext context, JobExecutionDelegate next, CancellationToken cancellationToken = default)
    {
        // Not calling next means the job does not run. The firing still completes, the listeners are
        // still notified, and the trigger is left where a successful execution leaves it.
        return flags.IsEnabled(context.JobDetail.Key) ? next(context, cancellationToken) : default;
    }
}

This is not a veto. A trigger listener's VetoJobExecution is the scheduler's refusal: it raises JobExecutionVetoed, and the firing ends there. A middleware that declines is invisible from outside.

Translating exceptions

A middleware runs outside the run shell's exception classification, so a JobExecutionException it throws is honoured exactly like one the job raised — including RefireImmediately and the unschedule flags — and a plain exception is wrapped the same way. That makes middleware the place to teach Quartz what a library's own failures mean:

public sealed class TransientFailureMiddleware : IJobExecutionMiddleware
{
    public async ValueTask Invoke(IJobExecutionContext context, JobExecutionDelegate next, CancellationToken cancellationToken = default)
    {
        try
        {
            await next(context, cancellationToken);
        }
        catch (HttpRequestException e) when (e.StatusCode == System.Net.HttpStatusCode.TooManyRequests)
        {
            // Quartz understands this; it does not understand HttpRequestException.
            throw new JobExecutionException(e) { RefireImmediately = true };
        }
    }
}

Warning

Catching a failure and awaiting a delay before calling next again is not a retry. It holds a thread-pool slot for the whole wait, and the attempt is lost if the process stops. A trigger's retry policy is the tool for that.

Per-firing state

One middleware instance serves every firing, so a field is the wrong place to keep anything about the firing in hand. Two things that are the right place:

An AsyncLocal<T>. The value travels with the execution context, so the job and everything it calls read the one their own firing set:

public sealed class TenantScopeMiddleware : IJobExecutionMiddleware
{
    public async ValueTask Invoke(IJobExecutionContext context, JobExecutionDelegate next, CancellationToken cancellationToken = default)
    {
        // An AsyncLocal, not a field: one instance of this middleware serves every firing the scheduler
        // performs, and several of them can be in flight at once.
        TenantScope.Current.Value = context.Trigger.Key.Group;
        try
        {
            await next(context, cancellationToken);
        }
        finally
        {
            TenantScope.Current.Value = null;
        }
    }
}

The job's dependency-injection scope. ConfigureJobScope runs once per firing, before anything in the scope is resolved, and is handed the TriggerFiredBundle:

builder.AddQuartz(q =>
{
    // Populated once per firing, before anything in the job's scope is resolved.
    q.ConfigureJobScope((scope, bundle, scheduler) =>
        scope.ServiceProvider.GetRequiredService<TenantHolder>().Tenant = bundle.Trigger.Key.Group);
});

No IServiceScope is threaded through Invoke, deliberately: the scope belongs to the firing rather than to any one middleware, and code that needs the firing itself can read it from IJobExecutionContextAccessor.Current, which is set for the whole execution — including inside the pipeline, on the way in and on the way out.

The cancellation token

Forward the token you were given. Passing a different one to next changes what the job's Execute parameter is without changing IJobExecutionContext.CancellationToken, so the two stop being the same token and a job that reads the context sees the wrong one. That is the trap in writing a timeout as a middleware.

Middleware or a listener?

Use middleware when you need toUse a listener when you need to
wrap the execution — a scope, a stopwatch, a transactionbe told that something happened
decide whether the job runs at allveto a fire (ITriggerListener.VetoJobExecution)
catch or translate what the job threwreact to the failure the run shell reports
set ambient state the job will readreact to scheduling events that are not executions at all — a trigger paused, the scheduler shutting down
act only on this scheduler's job executionsselect which jobs or triggers you hear about, with a matcher

Listeners stay notification-only, and none of this changes them. The two compose: a middleware can do its work and a listener can still record what happened.

See also

  • Trigger and Job Listeners
  • More About Jobs — job scopes and ConfigureJobScope
Help us by improving this page!
Last Updated: 8/31/26, 5:28 AM
Contributors: Marko Lahma, Claude Fable 5
Prev
Scheduler Listeners
Next
Job Stores