Creates and manages background tasks and scheduled jobs in Orchard Core. Covers IBackgroundTask, cron schedules, distributed locks, admin UI, and web farm behavior.
Ships in orchardcore. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
You are an Orchard Core expert. Generate background task implementations for Orchard Core.
IBackgroundTask and run on a cron schedule declared with [BackgroundTask].Startup.cs as IBackgroundTask singletons. Inject only singleton-safe services in the constructor; resolve scoped services (ISession, IContentManager, ...) from the IServiceProvider passed to DoWorkAsync.[BackgroundTask] properties: Title, Schedule (default */5 * * * *), Description, Enable (default true), LockTimeout and LockExpiration (milliseconds), and UsePipeline (build the tenant routing pipeline so the task can generate URLs).LockTimeout and LockExpiration are greater than 0: on a distributed lock (for example Redis), only one instance runs it at a time. Lock values are not limited to 30 seconds.OrchardCore.BackgroundTasks to manage tasks under Tools → Background Tasks: enable or disable, change the schedule, the lock values, and UsePipeline, overriding the attribute values. This requires the ManageBackgroundTasks permission.Title is shown with a title built from its type name (ChunkFileUploadBackgroundTask → Chunk File Upload). Prefer setting Title explicitly.0 0 31 2 *) shows the next run as never and only stops that task from running on schedule.ILogger for logging task execution and errors, and honor the CancellationToken.PollingTime, one minute by default, or MinimumIdleTime if 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.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;
}
}
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);
}
}
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;
}
}
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}}>();
}
}
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>();
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.
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):
DoWorkAsync is 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.
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.
LockTimeout and LockExpiration > 0) and enable a distributed lock such as OrchardCore.Redis.Lock so only one server runs it at a time; without a distributed lock the lock settings are ignored.LockExpiration above the longest expected run.ShellWarmup, a server only runs a tenant's tasks after that tenant served a request on it.{
"steps": [
{
"name": "Feature",
"enable": [
"OrchardCore.BackgroundTasks"
],
"disable": []
}
]
}
* * * * * — 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.AdminList shape (list name BackgroundTasks, see orchardcore-admin-lists) and offers bulk Enable and Disable actions.OrchardCore_BackgroundService configuration section to BackgroundService.BackgroundTaskState gained execution-state properties, and BackgroundTaskScheduler gained RequestRun(), Complete(), GetState() and GetNextStartTime().Title now display a humanized type name instead of the full type name.See references/background-tasks-examples.md for a complete example.
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
orchard-core, background-tasks, scheduled-jobs, cron, distributed-locks
/orchardcore:orchardcore-background-tasksfrom orchardcore
npx claudepluginhub crestapps/crestapps.agentskills --plugin orchardcore140 skills in this plugin
/orchardcore-adminGuidance for the Orchard Core admin panel, including admin controllers and routes, admin menu registration with AdminNavigationProvider, ocat editor forms grouped in cards, admin pages rendering Model.Editor, the UI text casing standard, TheAdmin layout and menu colors, admin branding, the Navbar shape, the Ctrl+K quick navigation palette and QuickNavigationSource, AdminSettings such as MenuBehavior, ShowBreadcrumb, DisplayQuickNavigation, DisplayTitlesInTopbar and ActionsLayout, the AdminDashboard shape, settings pages, and admin filters and zones. Use this skill when requests mention the Orchard Core admin panel, TheAdmin, admin controllers, admin menu registration, an icon on an admin menu item, the AdminSettings recipe step, quick navigation, navigation menu behavior, the admin URL prefix, UI text casing. Strong matches include OrchardCore.Admin, AdminSettings, AdminPermissions, AdminOptions, AdminAttribute, SiteDisplayDriver, IDisplayManager./orchardcore-admin-dashboardSkill for creating admin dashboard widgets in Orchard Core. Covers the DashboardWidget stereotype, DashboardPart position and sizing, the built-in HtmlDashboardWidget, ContentsMetadata and ContentsTags widget types, custom widget content types via recipe or migration, arranging widgets in Manage Dashboard mode, widget template customization, provisioning widgets with recipes, dashboard permissions, the DashboardBreadcrumbProvider Dashboard ancestor, and the AdminDashboardContent shape used when the feature is disabled. Use this skill when requests mention Orchard Core Admin Dashboard, Create and Configure Dashboard Widgets, Enabling Admin Dashboard, Widget Configuration Properties, dashboard widget recipes, Dashboard breadcrumb, or related implementation, setup, or troubleshooting work. Strong matches include OrchardCore.AdminDashboard, DashboardPart, DashboardBreadcrumbProvider, AccessAdminDashboard, ManageAdminDashboard.Other plugins' skills for the same job