Reference

AddTraxWorker

Package Trax.SchedulerNamespace Trax.Scheduler.ExtensionsSource WorkerExtensions.cs, LocalWorkerOptions.cs

Registers a standalone worker: a process that polls the background_job table and runs the jobs in it, with no scheduling or dispatching of its own. It is the one method of WorkerExtensions.

Signature

public static IServiceCollection AddTraxWorker(
    this IServiceCollection services,
    Action<LocalWorkerOptions>? configure = null
)

Parameters

ParameterTypeDefaultDescription
configureAction<LocalWorkerOptions>?nullSets the worker count, polling interval and timeouts

LocalWorkerOptions

PropertyTypeDefaultDescription
WorkerCountintEnvironment.ProcessorCountNumber of concurrent worker tasks polling for jobs. 1 to 256
PollingIntervalTimeSpan1 secondHow often idle workers poll for new jobs. Greater than zero, up to 30 days
VisibilityTimeoutTimeSpan30 minutesHow long a claimed job stays invisible before another worker can reclaim it (crash recovery). 1 second to 10 years
BatchSizeint1Jobs each worker claims per poll. At least 1
ShutdownTimeoutTimeSpan30 secondsGrace period for in-flight jobs during shutdown. 0 to 30 days

The same options as ConfigureLocalWorkers, with the same ranges.

Returns

The IServiceCollection, for chaining.

Behavior

  • AddTraxWorker throws InvalidOperationException listing every option outside its range.
  • The scheduler that fills background_job for this process registers its submitter with OverrideSubmitter(s => s.AddScoped<IJobSubmitter, PostgresJobSubmitter>()); otherwise it starts local workers of its own that compete with this one (see Remote Execution).

Registered services

AddTraxWorker() calls AddTraxJobRunner() and adds the worker service:

ServiceLifetimeDescription
All services from AddTraxJobRunner()(various)Execution pipeline (JobRunnerTrain, CancellationRegistry, etc.)
LocalWorkerOptionsSingletonWorker configuration
LocalWorkerServiceHosted ServiceBackground worker that polls background_job and executes trains

Not registered: the ManifestManager, the JobDispatcher, the polling services and the startup service.

A scheduler host whose AddScheduler already runs local workers (the default on Postgres) refuses AddTraxWorker(), in either order, with an InvalidOperationException: two sets of LocalWorkerOptions would silently replace one another. Configure the scheduler's pool with AddScheduler(scheduler => scheduler.ConfigureLocalWorkers(o => ...)) instead.

Compared with the scheduler's local workers

AspectScheduler (with Postgres)AddTraxWorker()
Used inFull scheduler processStandalone worker process
SchedulingYes (ManifestManager, JobDispatcher)No
DispatchingYes (writes to WorkQueue, background_job)No
ExecutionYes (LocalWorkerService)Yes (LocalWorkerService)
Job submitterRegisters PostgresJobSubmitterDoes not register any submitter

Several worker processes

Any number of worker processes may poll one database. Jobs are claimed with FOR UPDATE SKIP LOCKED, so each job is claimed by exactly one worker, with no coordination between processes.

┌── Worker Process A ──┐    ┌── Worker Process B ──┐
│  4 worker tasks       │    │  4 worker tasks       │
│  polling same table   │    │  polling same table   │
└───────────┬───────────┘    └───────────┬───────────┘
            │                            │
            └──────────┬─────────────────┘
                       ▼
              background_job table
              (SKIP LOCKED ensures
               no duplicate claims)

Shared requirements

A worker process:

  • References the train assemblies the scheduler passes to AddMediator(). Train types are resolved by fully-qualified name.
  • Connects to the scheduler's Postgres database. Metadata, manifests, and state are shared across all processes.
  • Registers the effects with AddTrax() and UsePostgres().

Examples

using Trax.Effect.Data.Postgres.Extensions;
using Trax.Effect.Extensions;
using Trax.Mediator.Extensions;
using Trax.Scheduler.Extensions;
 
var builder = WebApplication.CreateBuilder(args);
 
builder.Services.AddTrax(trax => trax
    .AddEffects(effects => effects
        .UsePostgres(connectionString)
    )
    .AddMediator(typeof(ISyncTrain).Assembly)
);
builder.Services.AddTraxWorker();
 
var app = builder.Build();
app.Run();

A worker whose assemblies hold [TraxAuthorize] trains does not start unless the mediator is told the process takes no submissions, since a worker has no ITrainAuthorizationService; the caller was checked when the job was queued:

builder.Services.AddTrax(trax => trax
    .AddEffects(effects => effects.UsePostgres(connectionString))
    .AddMediator(mediator => mediator
        .ScanAssemblies(typeof(ISyncTrain).Assembly)
        .AllowMissingAuthorizationService()));
builder.Services.AddTraxWorker();

See Authorization: Opting Out for Scheduler-Only Hosts. The Energy Hub sample runs this way.

Worker options:

builder.Services.AddTraxWorker(opts =>
{
    opts.WorkerCount = 4;
    opts.PollingInterval = TimeSpan.FromSeconds(2);
    opts.VisibilityTimeout = TimeSpan.FromMinutes(15);
    opts.ShutdownTimeout = TimeSpan.FromMinutes(1);
});

See also