RepletoryLib.BackgroundJobs.Abstractions 1.0.0

dotnet add package RepletoryLib.BackgroundJobs.Abstractions --version 1.0.0
                    
NuGet\Install-Package RepletoryLib.BackgroundJobs.Abstractions -Version 1.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="RepletoryLib.BackgroundJobs.Abstractions" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="RepletoryLib.BackgroundJobs.Abstractions" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="RepletoryLib.BackgroundJobs.Abstractions" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add RepletoryLib.BackgroundJobs.Abstractions --version 1.0.0
                    
#r "nuget: RepletoryLib.BackgroundJobs.Abstractions, 1.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package RepletoryLib.BackgroundJobs.Abstractions@1.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=RepletoryLib.BackgroundJobs.Abstractions&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=RepletoryLib.BackgroundJobs.Abstractions&version=1.0.0
                    
Install as a Cake Tool

RepletoryLib.BackgroundJobs.Abstractions

Background job abstractions and interfaces for the RepletoryLib ecosystem.

Part of the RepletoryLib ecosystem -- standalone, reusable .NET 10 libraries with zero business logic.

NuGet .NET 10 License: MIT


Overview

RepletoryLib.BackgroundJobs.Abstractions defines the contracts for background job scheduling in the RepletoryLib ecosystem. It provides interfaces for enqueueing fire-and-forget jobs, scheduling delayed jobs, and managing recurring jobs with cron expressions.

By programming against these interfaces, your application code stays decoupled from the job processing engine. You can switch between Hangfire, Quartz, or any future implementation without modifying business logic.

This package contains interfaces only -- no implementations. Choose an implementation package based on your needs.

Choosing an Implementation

Package Technology Best For
RepletoryLib.BackgroundJobs.Hangfire Hangfire Production job processing with dashboard, retries, and persistence

Key Features

  • IBackgroundJobService -- Enqueue, schedule, and manage recurring background jobs
  • IJobFilter -- Hook into job lifecycle (executing, executed, failed)
  • JobContext -- Rich metadata for job execution (ID, name, attempt number, creation time)
  • Expression-based API -- Jobs defined as Expression<Func<Task>> for type safety

Installation

dotnet add package RepletoryLib.BackgroundJobs.Abstractions

Or add to your .csproj:

<PackageReference Include="RepletoryLib.BackgroundJobs.Abstractions" Version="1.0.0" />

Note: RepletoryLib packages are published to a local BaGet feed. See the main repository README for feed configuration.

Dependencies

Package Type
RepletoryLib.Common RepletoryLib

Usage Examples

Fire-and-Forget Jobs

Enqueue a job to run immediately in the background:

using RepletoryLib.BackgroundJobs.Abstractions.Interfaces;

public class OrderController : ControllerBase
{
    private readonly IBackgroundJobService _jobs;

    public OrderController(IBackgroundJobService jobs) => _jobs = jobs;

    [HttpPost]
    public async Task<IActionResult> CreateOrder(CreateOrderRequest request)
    {
        var order = await _orderService.CreateAsync(request);

        // Send confirmation email in background (don't block the response)
        await _jobs.EnqueueAsync(() =>
            _emailService.SendOrderConfirmationAsync(order.Id));

        return Created($"/orders/{order.Id}", order);
    }
}

Scheduled (Delayed) Jobs

Schedule a job to run after a delay:

// Send a follow-up email 24 hours after order creation
await _jobs.ScheduleAsync(() =>
    _emailService.SendFollowUpAsync(orderId),
    TimeSpan.FromHours(24));

// Cancel a pending reservation if not confirmed within 15 minutes
await _jobs.ScheduleAsync(() =>
    _reservationService.CancelIfPendingAsync(reservationId),
    TimeSpan.FromMinutes(15));

Recurring Jobs

Set up recurring jobs with cron expressions:

// Run a daily report at 6:00 AM
await _jobs.AddOrUpdateRecurringAsync(
    "daily-sales-report",
    () => _reportService.GenerateDailySalesReportAsync(),
    "0 6 * * *");

// Process expired subscriptions every hour
await _jobs.AddOrUpdateRecurringAsync(
    "expire-subscriptions",
    () => _subscriptionService.ProcessExpiredAsync(),
    "0 * * * *");

// Run cleanup every Sunday at midnight
await _jobs.AddOrUpdateRecurringAsync(
    "weekly-cleanup",
    () => _cleanupService.RunWeeklyCleanupAsync(),
    "0 0 * * 0");

// Remove a recurring job
await _jobs.RemoveRecurringAsync("daily-sales-report");

Job Filters

Implement IJobFilter to hook into the job lifecycle for logging, metrics, or error handling:

using RepletoryLib.BackgroundJobs.Abstractions.Interfaces;
using RepletoryLib.BackgroundJobs.Abstractions.Models;

public class JobTelemetryFilter : IJobFilter
{
    private readonly ILogger<JobTelemetryFilter> _logger;

    public JobTelemetryFilter(ILogger<JobTelemetryFilter> logger) => _logger = logger;

    public void OnJobExecuting(JobContext context)
    {
        _logger.LogInformation(
            "Job {JobName} ({JobId}) starting, attempt #{Attempt}",
            context.JobName, context.JobId, context.AttemptNumber);
    }

    public void OnJobExecuted(JobContext context)
    {
        _logger.LogInformation(
            "Job {JobName} ({JobId}) completed successfully",
            context.JobName, context.JobId);
    }

    public void OnJobFailed(JobContext context, Exception exception)
    {
        _logger.LogError(exception,
            "Job {JobName} ({JobId}) failed on attempt #{Attempt}",
            context.JobName, context.JobId, context.AttemptNumber);
    }
}

API Reference

IBackgroundJobService

public interface IBackgroundJobService
{
    Task<string> EnqueueAsync(Expression<Func<Task>> job);
    Task<string> ScheduleAsync(Expression<Func<Task>> job, TimeSpan delay);
    Task AddOrUpdateRecurringAsync(string jobId, Expression<Func<Task>> job, string cronExpression);
    Task RemoveRecurringAsync(string jobId);
}
Method Returns Description
EnqueueAsync string (job ID) Enqueues a fire-and-forget job for immediate execution
ScheduleAsync string (job ID) Schedules a job to execute after the specified delay
AddOrUpdateRecurringAsync -- Creates or updates a recurring job with a cron expression
RemoveRecurringAsync -- Removes a recurring job by its ID

IJobFilter

public interface IJobFilter
{
    void OnJobExecuting(JobContext context);
    void OnJobExecuted(JobContext context);
    void OnJobFailed(JobContext context, Exception exception);
}

JobContext

public class JobContext
{
    public string JobId { get; }
    public string JobName { get; }
    public int AttemptNumber { get; }
    public DateTime CreatedAt { get; }
}
Property Type Description
JobId string Unique identifier for the job instance
JobName string Name of the job (derived from the method expression)
AttemptNumber int Current execution attempt (starts at 1, increments on retry)
CreatedAt DateTime When the job was originally enqueued

Integration with Other RepletoryLib Packages

Package Relationship
RepletoryLib.Common Direct dependency -- provides base types
RepletoryLib.BackgroundJobs.Hangfire Hangfire-based implementation of IBackgroundJobService
RepletoryLib.Workers Alternative approach for long-running background workers (polling, queue, scheduled)
RepletoryLib.Logging Log job execution with structured Serilog enrichers
RepletoryLib.Metrics Track job execution metrics (duration, failure rate) with Prometheus
RepletoryLib.Testing Write unit tests with mocked job service

Testing

Mock IBackgroundJobService with Moq or a simple in-memory implementation:

using Moq;

public class OrderControllerTests
{
    [Fact]
    public async Task CreateOrder_enqueues_email_job()
    {
        var mockJobs = new Mock<IBackgroundJobService>();
        mockJobs
            .Setup(j => j.EnqueueAsync(It.IsAny<Expression<Func<Task>>>()))
            .ReturnsAsync("job-123");

        var controller = new OrderController(mockJobs.Object);

        var result = await controller.CreateOrder(new CreateOrderRequest());

        mockJobs.Verify(
            j => j.EnqueueAsync(It.IsAny<Expression<Func<Task>>>()),
            Times.Once);
    }
}

Troubleshooting

Issue Solution
IBackgroundJobService not registered in DI Install and register an implementation package (BackgroundJobs.Hangfire)
Recurring job not executing Verify the cron expression is correct (use crontab.guru to validate)
Job ID returned is empty Check that the implementation is properly configured with persistence

License

This project is licensed under the MIT License.

Copyright (c) 2024-2026 Repletory.


For complete documentation, infrastructure setup, and configuration reference, see the RepletoryLib main repository.

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on RepletoryLib.BackgroundJobs.Abstractions:

Package Downloads
RepletoryLib.BackgroundJobs.Hangfire

Hangfire background job implementation for RepletoryLib

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.0 86 3/2/2026