Orchard Core Background Tasks - Prompt Templates
Create Background Tasks
You are an Orchard Core expert. Generate background task implementations for Orchard Core.
Guidelines
- Background tasks implement
IBackgroundTaskand run on a cron schedule declared with[BackgroundTask]. - Tasks are registered in
Startup.csasIBackgroundTasksingletons. Inject only singleton-safe services in the constructor; resolve scoped services (ISession,IContentManager, ...) from theIServiceProviderpassed toDoWorkAsync. - Each run gets its own tenant shell scope. The schedule is evaluated in the site time zone.
[BackgroundTask]properties:Title,Schedule(default*/5 * * * *),Description,Enable(defaulttrue),LockTimeoutandLockExpiration(milliseconds), andUsePipeline(build the tenant routing pipeline so the task can generate URLs).- A task is atomic when both
LockTimeoutandLockExpirationare greater than0: on a distributed lock (for example Redis), only one instance runs it at a time. Lock values are not limited to 30 seconds. - Enable
OrchardCore.BackgroundTasksto manage tasks under Tools → Background Tasks: enable or disable, change the schedule, the lock values, andUsePipeline, overriding the attribute values. This requires theManageBackgroundTaskspermission. - The admin list supports bulk actions: select several tasks and use Actions → Enable, Disable or Run now.
- The list shows each task's execution state (running or queued, last run outcome and duration, next run, failures, last error), and a Status filter for running/queued or failed tasks. Clicking a title opens a details page with run counts, the last error's stack trace and recent runs. Pages poll and update in place.
- Run now queues a task within a second or two regardless of its schedule and of whether it is enabled, unless it is already running or queued. It runs only on the server that handled the request, while scheduled runs happen on every server of a farm.
- The execution state lives in memory per server (reset on restart, not stored in the database), so in a web farm these admin pages need session affinity.
- A task without a
Titleis shown with a title built from its type name (ChunkFileUploadBackgroundTask→ Chunk File Upload). Prefer settingTitleexplicitly. - The editor rejects a schedule that is not a valid cron expression. An unusable schedule (for example
0 0 31 2 *) shows the next run as never and only stops that task from running on schedule. - Use
ILoggerfor logging task execution and errors, and honor theCancellationToken. - A task that takes longer than the polling time (
PollingTime, one minute by default, orMinimumIdleTimeif longer), or never completes, no longer blocks the background tasks of all tenants: it keeps running, the other tasks run without waiting for it, a warning is logged once, and it is not run again (on schedule or on demand) until it completes. See Long-Running Tasks. - Tasks should be idempotent and handle concurrent execution gracefully.
- Always seal classes.
Basic Background Task
using Microsoft.Extensions.Logging;
using OrchardCore.BackgroundTasks;
[BackgroundTask(
Title = "{{TaskTitle}}",
Schedule = "*/15 * * * *",
Description = "{{TaskDescription}}")]
public sealed class {{TaskName}} : IBackgroundTask
{
private readonly ILogger<{{TaskName}}> _logger;
public {{TaskName}}(ILogger<{{TaskName}}> logger)
{
_logger = logger;
}
public Task DoWorkAsync(IServiceProvider serviceProvider, CancellationToken cancellationToken)
{
_logger.LogInformation("Running {{TaskName}}...");
// Task logic here
return Task.CompletedTask;
}
}
Background Task with Service Dependencies
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using OrchardCore.BackgroundTasks;
using OrchardCore.ContentManagement;
using OrchardCore.ContentManagement.Records;
using YesSql;
[BackgroundTask(
Title = "{{TaskTitle}}",
Schedule = "0 */6 * * *",
Description = "{{TaskDescription}}")]
public sealed class {{TaskName}} : IBackgroundTask
{
private readonly ILogger<{{TaskName}}> _logger;
public {{TaskName}}(ILogger<{{TaskName}}> logger)
{
_logger = logger;
}
public async Task DoWorkAsync(IServiceProvider serviceProvider, CancellationToken cancellationToken)
{
// Resolve scoped services from the service provider of the run.
var contentManager = serviceProvider.GetRequiredService<IContentManager>();
var session = serviceProvider.GetRequiredService<ISession>();
_logger.LogInformation("Running {{TaskName}}...");
var items = await session
.Query<ContentItem, ContentItemIndex>(x =>
x.ContentType == "{{ContentType}}" && x.Published)
.ListAsync();
var count = 0;
foreach (var item in items)
{
if (cancellationToken.IsCancellationRequested)
{
break;
}
// Process item
count++;
}
_logger.LogInformation("{{TaskName}} completed. Processed {Count} items.", count);
}
}
Atomic Background Task
Use a lock when the task must not run concurrently on several instances of a web farm. Values are in milliseconds and may exceed 30 seconds.
using OrchardCore.BackgroundTasks;
[BackgroundTask(
Title = "Nightly export",
Schedule = "0 3 * * *",
Description = "Exports data once per night across all instances.",
LockTimeout = 3_000,
LockExpiration = 300_000,
UsePipeline = true)]
public sealed class NightlyExportTask : IBackgroundTask
{
public Task DoWorkAsync(IServiceProvider serviceProvider, CancellationToken cancellationToken)
{
// Long running work; the lock is held up to 5 minutes.
return Task.CompletedTask;
}
}
Registering a Background Task
using Microsoft.Extensions.DependencyInjection;
using OrchardCore.BackgroundTasks;
using OrchardCore.Modules;
public sealed class Startup : StartupBase
{
public override void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IBackgroundTask, {{TaskName}}>();
}
}
Reacting to Task Execution
Implement IBackgroundTaskEventHandler to run code before and after every task of the tenant (for example telemetry). BackgroundTaskEventContext exposes Name, Tenant, Services, and Exception.
using OrchardCore.BackgroundTasks;
public sealed class TaskTelemetryHandler : IBackgroundTaskEventHandler
{
public Task ExecutingAsync(BackgroundTaskEventContext context, CancellationToken cancellationToken)
=> Task.CompletedTask;
public Task ExecutedAsync(BackgroundTaskEventContext context, CancellationToken cancellationToken)
{
if (context.HasException)
{
// Report context.Exception for context.Name on context.Tenant.
}
return Task.CompletedTask;
}
}
services.AddScoped<IBackgroundTaskEventHandler, TaskTelemetryHandler>();
Background Service Configuration
The host polls every tenant's tasks. Configure it in appsettings.json of the startup project under OrchardCore:BackgroundService (the 3.x name OrchardCore_BackgroundService is deprecated):
{
"OrchardCore": {
"BackgroundService": {
"PollingTime": "00:01:00",
"MinimumIdleTime": "00:00:10",
"ShellWarmup": false,
"MaxRecentRuns": 10
}
}
}
PollingTime (default 00:01:00) is the time between two executions of a tenant's tasks, and also bounds how long the service waits for one task before running the others. MinimumIdleTime (default 00:00:10) is the idle time before a tenant's tasks are triggered and between tasks. MaxRecentRuns (default 10) is the number of completed runs kept in memory per task for the details page.
Long-Running Tasks
The background service runs the due tasks of a tenant one after the other, and the tenants in parallel. It waits for each task at most for PollingTime (or MinimumIdleTime if longer):
- A task still running after that time keeps running while the other tasks run; a warning is logged once for the run.
- Until it completes, the task is not run again, neither on schedule nor with Run now. Once it completes, it runs again if a scheduled occurrence passed meanwhile.
- When the application stops, the token passed to
DoWorkAsyncis cancelled and running tasks are awaited up to the host shutdown timeout.
The service can't stop a task that ignores its CancellationToken or blocks its thread. Give calls to services that may not respond a timeout so the task completes. Several long tasks due at the same time in one tenant are still awaited one after the other, so they can delay the others by several polling times.
Reading the Execution State from Code
IBackgroundTaskMonitor (namespace OrchardCore.BackgroundTasks) is a host-level service registered by AddBackgroundService(): GetStatesAsync(tenant), GetStateAsync(tenant, name) and RequestRunAsync(tenant, name). Inject IEnumerable<IBackgroundTaskMonitor> when the code may run without the background service. The task name is the full type name returned by IBackgroundTask.GetTaskName().
using OrchardCore.BackgroundTasks;
using OrchardCore.Environment.Shell;
public sealed class NightlyExportStatus
{
private readonly IBackgroundTaskMonitor _monitor;
private readonly ShellSettings _shellSettings;
public NightlyExportStatus(IBackgroundTaskMonitor monitor, ShellSettings shellSettings)
{
_monitor = monitor;
_shellSettings = shellSettings;
}
public async Task<bool> LastRunFailedAsync()
{
var state = await _monitor.GetStateAsync(_shellSettings.Name, typeof(NightlyExportTask).FullName);
return state?.LastRun?.Result == BackgroundTaskRunResult.Failed;
}
// Returns Queued, AlreadyQueued, AlreadyRunning or NotFound.
public Task<BackgroundTaskRunRequestResult> RunNowAsync()
=> _monitor.RequestRunAsync(_shellSettings.Name, typeof(NightlyExportTask).FullName);
}
BackgroundTaskState exposes Status, QueuedTime, NextStartTime, LastRun, RunCount, FailureCount and RecentRuns. Right after a tenant starts, RequestRunAsync can return NotFound until the next polling, which the request triggers; retry a moment later.
Web Farms
- Scheduled tasks run on every server, each with its own schedule. Make a task atomic (
LockTimeoutandLockExpiration> 0) and enable a distributed lock such asOrchardCore.Redis.Lockso only one server runs it at a time; without a distributed lock the lock settings are ignored. - Set
LockExpirationabove the longest expected run. - Without
ShellWarmup, a server only runs a tenant's tasks after that tenant served a request on it.
Enabling Background Tasks Feature
{
"steps": [
{
"name": "Feature",
"enable": [
"OrchardCore.BackgroundTasks"
],
"disable": []
}
]
}
Common Cron Schedule Expressions
* * * * *— Every minute.*/5 * * * *— Every 5 minutes.*/15 * * * *— Every 15 minutes.0 * * * *— Every hour.0 */6 * * *— Every 6 hours.0 0 * * *— Daily at midnight.0 0 * * 0— Weekly on Sunday at midnight.0 0 1 * *— Monthly on the 1st at midnight.
Upgrading from 3.x
- The Background Tasks admin list now renders through the shared
AdminListshape (list nameBackgroundTasks, seeorchardcore-admin-lists) and offers bulk Enable and Disable actions. - The editor no longer caps Lock timeout and Lock expiration at 30000 ms.
- Rename the
OrchardCore_BackgroundServiceconfiguration section toBackgroundService. BackgroundTaskStategained execution-state properties, andBackgroundTaskSchedulergainedRequestRun(),Complete(),GetState()andGetNextStartTime().- An invalid stored schedule no longer stops the background tasks of all tenants; it only prevents that task from running on schedule.
- Tasks without a
Titlenow display a humanized type name instead of the full type name.
See references/background-tasks-examples.md for a complete example.