Orchardcore background tasks

From CrestApps/CrestApps.AgentSkills · View interactive version

Orchardcore background tasks is an AI agent skill from the GitHub repository CrestApps/CrestApps.AgentSkills. Skill for creating background tasks and scheduled jobs in Orchard Core. Covers IBackgroundTask implementation, long-running and never-completing tasks bounded by PollingTime, the BackgroundTask attribute (Title, Schedule, Description, Enable, LockTimeout, LockExpiration, UsePipeline), atomic tasks w

How to use this skill

Skill file

Orchard Core Background Tasks - Prompt Templates

Create Background Tasks

You are an Orchard Core expert. Generate background task implementations for Orchard Core.

Guidelines

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):

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

Enabling Background Tasks Feature

{
  "steps": [
    {
      "name": "Feature",
      "enable": [
        "OrchardCore.BackgroundTasks"
      ],
      "disable": []
    }
  ]
}

Common Cron Schedule Expressions

Upgrading from 3.x

See references/background-tasks-examples.md for a complete example.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.