NCronJob Compact Reference¶
This file is a compact Markdown entry point for assistants, automation, and quick retrieval.
What NCronJob is¶
NCronJob is an in-process .NET scheduler for recurring jobs, startup jobs, and manually triggered jobs. It is intended for applications that want a native IHostedService-based scheduler without adding a database-backed platform such as Hangfire or Quartz.
Main concepts¶
- Typed jobs implement
IJob, orIJob<TParameter>to accept a parameter read viaIJobExecutionContext<TParameter>.Parameter - Minimal jobs are delegates registered via
AddNCronJob(...) - Recurring jobs use cron expressions
- Instant jobs are triggered through
IInstantJobRegistry - Startup jobs use
RunAtStartup(...) - Runtime-managed jobs use
IRuntimeJobRegistry
Primary APIs¶
Register jobs¶
AddNCronJob(...)for typed jobs and builder-based registrationAddNCronJob(Delegate jobDelegate, string cronExpression, TimeZoneInfo? timeZoneInfo = null)AddNCronJob(Delegate jobDelegate, string cronExpression, TimeZoneInfo? timeZoneInfo, string jobName)
Start startup jobs¶
UseNCronJobAsync(IHost)UseNCronJob(IHost)
Only required when at least one job uses RunAtStartup(...).
Trigger work manually¶
IInstantJobRegistry.RunInstantJob(...)IInstantJobRegistry.RunScheduledJob(...)IInstantJobRegistry.ForceRunInstantJob(...)IInstantJobRegistry.ForceRunScheduledJob(...)
Manage recurring jobs at runtime¶
IRuntimeJobRegistry.TryRegister(...)IRuntimeJobRegistry.RemoveJob(...)IRuntimeJobRegistry.UpdateSchedule(...)IRuntimeJobRegistry.UpdateParameter(...)IRuntimeJobRegistry.TryGetSchedule(...)IRuntimeJobRegistry.TryGetNextOccurrence(...)IRuntimeJobRegistry.EnableJob(...)IRuntimeJobRegistry.DisableJob(...)
Configure scheduling limits¶
WithTimeout(TimeSpan)on a job cancels a run once its execution exceeds the duration (retries share one window);Timeout.InfiniteTimeSpandisables it. A timed-out run is reported asCancelledand triggers no success or fault dependencies. Also available for dependent jobs and startup jobsWithJobRunExpiry(TimeSpan)on a job andWithDefaultJobRunExpiry(TimeSpan)on the options limit how late a queued run may start (default: 10 minutes); expired runs are dropped without executingSkipIfStillRunning()on a job drops a cron occurrence asSkippedwhen the job is still running at its own concurrency limit, instead of queueing itWithMaxDegreeOfParallelism(int)on the options builder sets the scheduler-wide maximum of concurrently executing jobs; the value must be greater than zero
Cron expressions and macros¶
WithCronExpression(...) and AddNCronJob(Delegate, ...) accept 5-part expressions, 6-part expressions with seconds, or one of these macros (evaluated in the configured time zone):
| Macro | Equivalent |
|---|---|
@every_second |
* * * * * * |
@every_minute |
* * * * * |
@hourly |
0 * * * * |
@daily / @midnight |
0 0 * * * |
@weekly |
0 0 * * 0 |
@monthly |
0 0 1 * * |
@yearly / @annually |
0 0 1 1 * |
Unknown macros throw an ArgumentException.
CronSchedule.IsValid(expression, out error) validates an expression with the same rules, and CronSchedule.GetNextOccurrences(expression, count, from, timeZone) previews its upcoming UTC occurrences.
Observability¶
- Log scopes: every job run executes in a log scope, so all entries written during the run (including the job’s own
ILogger<T>) carryJobName,JobRunId,CorrelationIdandTriggerType(Cron,Instant,StartuporDependent). Scopes must be enabled in the logging provider, e.g.IncludeScopesfor the console logger - Tracing: each job run is an
Activityfrom theActivitySourcenamedNCronJobDiagnostics.ActivitySourceName("NCronJob"). Subscribe withAddOpenTelemetry().WithTracing(t => t.AddSource(NCronJobDiagnostics.ActivitySourceName)). Tags:ncronjob.job.name,ncronjob.correlation_id,ncronjob.trigger_type,ncronjob.attemptsanderror.typeon failure; a failed run sets the status toError - Metrics: a
MeternamedNCronJobDiagnostics.MeterName("NCronJob"). Subscribe withAddOpenTelemetry().WithMetrics(m => m.AddMeter(NCronJobDiagnostics.MeterName)). Countersncronjob.job.runs,ncronjob.job.failures,ncronjob.job.retries,ncronjob.job.skipped,ncronjob.job.expiredand histogramncronjob.job.duration(seconds, including retries), tagged withncronjob.job.nameandncronjob.trigger_type - Progress:
IJobExecutionProgressReporterobserves run state changes, including each run’sParameterandTriggerType - Dashboard: the
NCronJob.Dashboardpackage addsservices.AddNCronJobDashboard()andapp.MapNCronJobDashboard("/ncronjob", e => e.RequireAuthorization(...)). It is a Blazor Server UI for jobs, startup jobs, dependencies, live runs and triggering jobs with a JSON parameter. Run history is in memory only
Practical rules¶
- Name jobs when you need runtime management
- Name jobs when the same job type is registered more than once
- Use
RunInstantJob("name")to avoid ambiguity with duplicate job types - Parameters are passed by reference and are not serialized
- Parameters must be assignable to the job’s
TParameter; a wrong type throwsArgumentExceptionat registration or trigger time, a missing one isdefault(TParameter) - Forced instant and scheduled jobs bypass queueing and concurrency safeguards
- Startup jobs require
UseNCronJobAsync()orUseNCronJob() - In tests, register
FakeTimeProviderbeforeAddNCronJobandAdvanceit to fire cron runs - Jobs have no execution timeout by default; jobs must observe the
CancellationTokenforWithTimeoutto take effect
Best starting points¶
- First setup: Getting Started
- Docs guide: Documentation Map
- Agents: Agent & Automation Guide
Feature index¶
- Define and Schedule Jobs
- Passing Parameters
- Triggering instant jobs
- Concurrency control
- Global concurrency
- Job timeouts and run expiry
- Retry support
- Minimal API
- Running Startup Jobs
- Model Dependencies
- Notifications
- Conditional Job Scheduling
- Dynamic Job Control
- Observing job progress, tracing and metrics
- Log level and log scopes
- Testing jobs and schedules
- Known gotchas
- Dashboard
Sample projects¶
sample/MinimalSample— https://github.com/NCronJob-Dev/NCronJob/tree/main/sample/MinimalSamplesample/NCronJobSample— https://github.com/NCronJob-Dev/NCronJob/tree/main/sample/NCronJobSamplesample/RunOnceSample— https://github.com/NCronJob-Dev/NCronJob/tree/main/sample/RunOnceSample