Scheduled jobs (.NET)
For an app that has recurring work: refresh data from outside sources every 15 minutes, sweep for check-ins that are due, expire things, sync counts. Register the jobs with TenancyEngine.Sdk (2.17.0) and the platform scheduler runs them for you: on one replica per tick, with run history, a per-job timeout, jitter, backoff, and a diagnostics endpoint that is never public. You write only the job; you do not write a BackgroundService loop, a lock, or a retry timer.
services.AddTenancyEngineScheduledJobs(o =>
{
o.AppName = "my-app";
o.UsePostgresAdvisoryLock(connectionString); // leader election
})
.AddJob<ScraperRefreshJob>()
.AddJob<CheckInSweepJob>();You reference one package, TenancyEngine.Sdk. The scheduler and the lock live in TenancyEngine.Scheduling and TenancyEngine.ReliableDelivery; they arrive as transitive dependencies of TenancyEngine.Sdk and your code never names them (no using TenancyPlatform...). Do not add either as a direct PackageReference.
Availability. This facade is in the private-feed build of
TenancyEngine.Sdk(nuget.cyntrix.ca), 2.17.0 and later. The copy on nuget.org is a public package and cannot depend on private packages, so it does not contain theTenancyEngine.Sdk.Schedulingnamespace: code written against this page fails to compile against the nuget.org package (error CS0234: The type or namespace name 'Scheduling' does not exist in the namespace 'TenancyEngine.Sdk'). Restore from the feed, as every TenancyEngine app already does.
Guarantee: at-least-once, so every job must be idempotent. The scheduler runs a job on one replica per tick in normal operation. It does not give exactly-once or mutual exclusion that survives every failure. Two runs of the same job can overlap, or a run can repeat, when: (1) a job ignores its cancellation token past
Timeout + TimeoutGrace: it is failed and abandoned, the lock is released, and the next tick on any replica starts while the abandoned task may still be running (an ERROR is logged andtenancyengine.scheduling.abandoned_runscounts it); (2) the lock connection drops (the Postgres advisory lock lives on one session and is not renewed or fenced; a network cut, a database failover or an idle-kill releases it while the job is still running); (3) a Redis lease expires (Timeout + TimeoutGrace + 30 s) before a hung job returns; (4) a run is cancelled midway by a shutdown or timeout and the next run repeats the work. The scheduler cannot fence a job that has already started. Make each run safe to repeat or overlap: idempotency keys on writes, "claim then process" updates, and unique constraints. Do not rely on the lock for correctness of money, messages sent, or anything not repeatable.
What you get
| One leader per tick | N replicas run the same scheduler; for each job and tick one acquires the lock and the others skip the tick. Skips are counted (metric and a diagnostics counter), not stored in history. See the at-least-once guarantee above for when this does not hold. |
| Sequential per job | Within a replica a job's next wait starts after its run ends, and the lock is held while it runs. This is not a fence: see the failure cases above. |
| No catch-up burst | After an outage the job runs once, not once per missed interval. Your job decides what is due when it wakes up (see the eligibility rules in the sample). |
| Exception isolation | A job that throws is recorded as failed and retried with exponential backoff; it never stops another job's loop or the host. |
| Per-run timeout | The token you receive is cancelled at the timeout. A job that ignores it is failed and abandoned after a grace period, so it cannot hold the lock forever. |
| Shutdown | On host shutdown the token is cancelled; the run is recorded as Cancelled, not Failed, and the lock is released. |
| Jitter | A random 0 to MaxJitter is added to every wait so restarted replicas do not hit the lock together. |
| History and signals | Every tick (run, skip, failure, cancel) is stored, logged, traced (ActivitySource scheduledjob.tick) and counted. |
| Diagnostics | MapTenancyEngineScheduledJobsDiagnostics("policy"): overview and recent runs, behind your authorization policy. |
Choose the lock
Exactly one is required. Registration throws without one: an app that forgot the lock would run every job on every replica.
| Call | Use it when | Notes |
|---|---|---|
UsePostgresAdvisoryLock(connectionString) | Your app has Postgres (most do). Default choice. | Session-level advisory lock on a dedicated connection; released the moment the holder dies or the connection drops. No lock table. Use a direct Postgres connection, NOT a transaction-mode pooler: PgBouncer in transaction mode (the dev stack's :25436) breaks session locks, and registration logs a warning when the string looks like one (port 6432/25436 or a pgbouncer/pooler host). Each lock held pins one connection for the whole run, so size your connection limit for the number of jobs that can run at once. The lock key is prefixed with AppName, so two apps with the same job name in one database do not block each other. Run history also goes to Postgres (scheduled_job_runs) so every replica shows the same history. |
UseRedisLock(IConnectionMultiplexer) | The app has no Postgres but has Redis. | SET NX with a lease sized to the job's timeout + grace + 30 s; a Redis outage means "not acquired" (tick skipped). Needs AppName (key namespace). History stays per-replica in memory unless you add UsePostgresHistory. |
UseLock(ITenancyEngineJobLock) | You have another shared store (a database row lock). | Must return null immediately when the key is held, and must never report "acquired" without holding it. |
UseSingleReplicaInProcessLock() | Local development, tests, or a deployment pinned to one replica. | Protects only inside one process. With two replicas both run every tick. |
The existing platform cache (ICacheClient) is deliberately not a lock provider: it has get and set but no atomic "set if absent", and a lock built on get-then-set races.
Options
| Option | Default | Meaning |
|---|---|---|
AppName | none | Required with every lock except the in-process one. Prefixes lock keys so apps sharing a database or Redis never block each other. Not a place for secrets or personal data. |
MaxJitter | 5 s | Random extra wait on every tick. TimeSpan.Zero turns it off. |
DefaultTimeout | 10 min | Per-run timeout for a job that sets none. A job overrides it with its Timeout property. |
TimeoutGrace | 30 s | How long a job may take to stop after cancellation before it is failed and abandoned. |
BackoffBase / BackoffMaxInterval | 30 s / 30 min | After a failure the next wait is min(base * 2^(failures-1), max); one success resets it. |
HistoryRetentionPerJob | 200 | Runs kept per job. |
UseInMemoryHistory() / UsePostgresHistory(cs) | Postgres with the Postgres lock, otherwise memory | Where run history lives. |
EnsureHistorySchema | true | When false the SDK never runs CREATE TABLE; you create the table (below). |
History table (Postgres)
By default the first history write runs CREATE TABLE IF NOT EXISTS on the history connection, so that role needs CREATE rights on the schema the first time. If your role must not have them, set o.EnsureHistorySchema = false and create the table once (migration or DBA):
CREATE TABLE IF NOT EXISTS scheduled_job_runs (
id BIGSERIAL PRIMARY KEY,
job_name TEXT NOT NULL,
started_utc TIMESTAMPTZ NOT NULL,
duration_ms DOUBLE PRECISION NOT NULL,
outcome TEXT NOT NULL,
consecutive_failure_count INTEGER NOT NULL DEFAULT 0,
error_message TEXT NULL,
error_stack_trace TEXT NULL,
host_instance TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS ix_scheduled_job_runs_job_started ON scheduled_job_runs (job_name, started_utc DESC);The role then needs INSERT, SELECT and DELETE on it (retention prunes old rows). The SDK stores no stack traces and no skipped ticks; error text is redacted and cut to 300 characters. EnsureHistorySchema needs TenancyEngine.Scheduling 1.2.0 or later (a transitive dependency of this SDK version).
Writing a job
A job is a singleton with a fixed interval. It gets a fresh DI scope per run in context.Services (resolve your DbContext there, never in the constructor) and a token to honour. Put the rules that decide what is eligible inside the job: the schedule says when it wakes up, the job says what is due.
The sample below is a whole app: a scraper refresh that only touches sources not refreshed in 6 hours, and a check-in sweep that applies per-household quiet hours and a weekly cap. It is compiled by the SDK test suite against the real API.
// file: Ports.cs
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
public sealed record ScrapeSource(Guid Id, string Url, DateTimeOffset? LastRefreshedUtc);
public interface ISourceCatalog
{
Task<IReadOnlyList<ScrapeSource>> ListAsync(CancellationToken ct);
Task RefreshAsync(ScrapeSource source, CancellationToken ct);
}
public sealed record HouseholdCheckIn(Guid HouseholdId, string TimeZoneId, DateTimeOffset? LastQueuedUtc);
public interface ICheckInStore
{
Task<IReadOnlyList<HouseholdCheckIn>> ListOptedInAsync(CancellationToken ct);
// Idempotent on the key: queueing the same household for the same week twice stores one row.
Task QueueAsync(Guid householdId, string idempotencyKey, CancellationToken ct);
}
public interface IHouseholdPager
{
// Keyset paging: ids after the cursor, ordered, at most `take`. Never load every household at once.
Task<IReadOnlyList<Guid>> NextPageAsync(Guid? after, int take, CancellationToken ct);
}
public interface IHouseholdWork
{
// Idempotent: a repeated or overlapping run for the same household and week must be harmless.
Task ProcessAsync(Guid householdId, CancellationToken ct);
}// file: ScraperRefreshJob.cs
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using TenancyEngine.Sdk.Scheduling;
public sealed class ScraperRefreshJob : ITenancyEngineScheduledJob
{
private static readonly TimeSpan MinAge = TimeSpan.FromHours(6);
public string Name => "scraper-refresh";
public TenancyEngineJobSchedule Schedule { get; } =
TenancyEngineJobSchedule.Every(TimeSpan.FromMinutes(15), initialDelay: TimeSpan.FromMinutes(1));
public TimeSpan? Timeout => TimeSpan.FromMinutes(10);
public async Task RunAsync(TenancyEngineJobContext context, CancellationToken ct)
{
var catalog = context.Services.GetRequiredService<ISourceCatalog>();
var log = context.Services.GetRequiredService<ILogger<ScraperRefreshJob>>();
// Eligibility lives here: only sources that have not been refreshed recently.
var due = (await catalog.ListAsync(ct))
.Where(s => s.LastRefreshedUtc is null || context.StartedUtc - s.LastRefreshedUtc >= MinAge)
.ToList();
var failed = 0;
foreach (var source in due)
{
ct.ThrowIfCancellationRequested();
try
{
await catalog.RefreshAsync(source, ct);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
failed++; // one bad source must not stop the others
log.LogWarning(ex, "Refresh of source {SourceId} failed.", source.Id);
}
}
// Surface partial failure so it shows in the history and backs the job off.
if (failed > 0)
throw new InvalidOperationException($"{failed} of {due.Count} source(s) failed to refresh.");
}
}// file: CheckInSweepJob.cs
using System;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using TenancyEngine.Sdk.Scheduling;
public sealed class CheckInSweepJob : ITenancyEngineScheduledJob
{
public string Name => "check-in-sweep";
public TenancyEngineJobSchedule Schedule { get; } = TenancyEngineJobSchedule.Every(TimeSpan.FromMinutes(30));
public async Task RunAsync(TenancyEngineJobContext context, CancellationToken ct)
{
var store = context.Services.GetRequiredService<ICheckInStore>();
foreach (var household in await store.ListOptedInAsync(ct))
{
ct.ThrowIfCancellationRequested();
if (!IsEligible(household, context.StartedUtc)) continue;
var utc = context.StartedUtc.UtcDateTime;
await store.QueueAsync(household.HouseholdId, $"checkin:{household.HouseholdId:N}:{ISOWeek.GetYear(utc)}-W{ISOWeek.GetWeekOfYear(utc)}", ct);
}
}
// Local eligibility rules: the household's own quiet hours (21:00 to 08:00 local) and at most one per 6 days.
public static bool IsEligible(HouseholdCheckIn household, DateTimeOffset nowUtc)
{
var zone = TimeZoneInfo.FindSystemTimeZoneById(household.TimeZoneId);
var local = TimeZoneInfo.ConvertTime(nowUtc, zone);
if (local.Hour >= 21 || local.Hour < 8) return false;
return household.LastQueuedUtc is null || nowUtc - household.LastQueuedUtc >= TimeSpan.FromDays(6);
}
}// file: HouseholdFanOutJob.cs
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using TenancyEngine.Sdk.Scheduling;
// The per-entity pattern: ONE job wakes up, pages through the entities in batches, processes each with bounded parallelism and its own scope,
// isolates each entity's failure, and rethrows one aggregate at the end so the run shows as failed and backs off.
public sealed class HouseholdFanOutJob : ITenancyEngineScheduledJob
{
private const int PageSize = 200;
private const int MaxParallel = 4;
public string Name => "household-fan-out";
public TenancyEngineJobSchedule Schedule { get; } = TenancyEngineJobSchedule.Every(TimeSpan.FromMinutes(10));
public TimeSpan? Timeout => TimeSpan.FromMinutes(8); // keep it under the interval so runs do not queue up behind each other
public async Task RunAsync(TenancyEngineJobContext context, CancellationToken ct)
{
var pager = context.Services.GetRequiredService<IHouseholdPager>();
var scopes = context.Services.GetRequiredService<IServiceScopeFactory>();
var failures = new ConcurrentBag<Exception>();
Guid? cursor = null;
while (true)
{
ct.ThrowIfCancellationRequested();
var page = await pager.NextPageAsync(cursor, PageSize, ct);
if (page.Count == 0) break;
await Parallel.ForEachAsync(page, new ParallelOptions { MaxDegreeOfParallelism = MaxParallel, CancellationToken = ct }, async (id, token) =>
{
try
{
await using var scope = scopes.CreateAsyncScope(); // one scope per entity, never shared across threads
await scope.ServiceProvider.GetRequiredService<IHouseholdWork>().ProcessAsync(id, token);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
failures.Add(new InvalidOperationException("Household work failed.", ex)); // keep the id out of the message text
}
});
cursor = page[^1];
}
if (!failures.IsEmpty)
throw new AggregateException($"{failures.Count} household(s) failed.", failures);
}
}// file: Program.cs
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using TenancyEngine.Sdk.Scheduling;
var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("PostgreSQL")
?? throw new InvalidOperationException("ConnectionStrings:PostgreSQL is required.");
builder.Services.AddTenancyEngineScheduledJobs(o =>
{
o.AppName = "family-planner";
o.UsePostgresAdvisoryLock(connectionString); // leader election: one replica per tick
o.DefaultTimeout = TimeSpan.FromMinutes(5);
})
.AddJob<ScraperRefreshJob>()
.AddJob<CheckInSweepJob>()
.AddJob<HouseholdFanOutJob>();
// Your real authentication scheme goes here; the diagnostics endpoint is only as strong as this policy.
builder.Services.AddAuthentication();
builder.Services.AddAuthorization(o => o.AddPolicy("operators", p => p.RequireRole("operator")));
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapTenancyEngineScheduledJobsDiagnostics("operators"); // GET /_tenancyengine/scheduled-jobs
app.Run();Keep secrets and personal data out of job names,
AppNameand exception messages. Names become lock keys, log fields and history rows; exception messages are stored (redacted and cut to 300 characters, best effort) and shown to operators. Use opaque ids, never names, emails or connection strings.
The third job, HouseholdFanOutJob, is the pattern for "do something for every household" (the Roots2Excel shape): there is no dynamic per-entity schedule and no backpressure in the scheduler, so you fan out inside one job. Page by keyset, bound the parallelism, give each entity its own scope, isolate each failure, check the token between pages, keep the timeout under the interval, and rethrow an aggregate at the end. Work per entity must be idempotent (see the guarantee above).
Your own services (ISourceCatalog, ICheckInStore, IHouseholdPager, IHouseholdWork) are registered like any other scoped service. The check-in sample queues rows only; sending the email is a separate platform facade that is not part of this release (tracked in tenancyengine#1620), and nothing here sends mail.
Diagnostics endpoint
app.MapTenancyEngineScheduledJobsDiagnostics("policy-name") maps two read-only routes:
GET /_tenancyengine/scheduled-jobs-- every job with its health (Healthy,Failing,Overdue,Starting,NeverRun,Observed), last run, and 24 hour counts.GET /_tenancyengine/scheduled-jobs/{jobName}/runs?limit=50-- recent runs, newest first. 404 for a name that is not a registered job.
It is never public. The policy name is a required argument, and an empty one throws at startup. An unauthenticated call gets 401, an authenticated caller the policy rejects gets 403, and a policy name that does not exist fails the request instead of opening the endpoint. Responses carry no stack traces and no host or process names; error messages are redacted (connection-string pairs, URL credentials, bearer tokens, long tokens, IPv4 addresses) and cut to 300 characters. Each job also shows skippedTicksSinceProcessStart, the ticks this replica skipped because another was leader. The routes are yours to place: pass pattern: to move them, and keep them off the public host.
Testing your jobs
Test the job class directly: build a TenancyEngineJobContext with a test IServiceProvider. To test the scheduling itself in your app, register with UseSingleReplicaInProcessLock(), resolve the JobScheduler hosted service, and call RunNowAsync(jobName, ct). The SDK's own suite proves two scheduler instances running one tick with a shared lock produce one execution, a failing job does not stop its neighbours, a stuck job is abandoned, and shutdown cancels a run.
Metrics
Meter TenancyEngine.Sdk.Scheduling: tenancyengine.scheduling.abandoned_runs (alert on any non-zero value) and tenancyengine.scheduling.skipped_ticks. The platform scheduler's own meter also reports runs, durations and leadership.
What this does not do
- No dynamic per-entity schedules and no backpressure. Fan out inside one job (
HouseholdFanOutJob). - No cron and no per-entity dates. The schedule is a fixed interval. "Send each household its own reminder at its own time" is a sweep that runs often and decides what is due, as in the sample.
- No retry of a missed tick. A tick missed while every replica was down is not replayed; the next tick finds the work still due.
- No work queue. A job that must process each item exactly once needs idempotency in the job (the sample uses an idempotency key), because a run can be cancelled midway.
- Temporal is not involved. The durable automation runtime (
AutomationRuntime__Enabled) stays off and is a separate feature.
Versions
TenancyEngine.Sdk 2.17.0 depends on TenancyEngine.Scheduling 1.2.0 (new: the ensureSchema option of the Postgres history store; default behaviour unchanged for its other consumers) and TenancyEngine.ReliableDelivery 1.4.5, both transitively. When a release changes Scheduling, the SDK takes a new minor version in the same change, so one SDK version means one tested pair.
Restore note. The private-feed net8.0/net9.0 assets now require Microsoft.Extensions.* 9.0.19 or later (the scheduler's floor); this applies to every private-feed user of the SDK, not only to apps that use jobs, because the packages are one dependency set. An app that pins Microsoft.Extensions.Logging.Abstractions, Configuration.Abstractions, Configuration or Caching.Memory between 9.0.0 and 9.0.18 gets NU1605 on restore: raise the pin.