LESSON 11 OF 14

11. Delayed, Recurring, and Continuation Job Scenarios

In this lesson, you will schedule future operations, create recurring Hangfire tasks, and start continuation jobs after successful completion of another job.

35 dk 48

Introduction

In the previous lesson, we installed Hangfire and created fire-and-forget jobs. A fire-and-forget job starts in the background as soon as possible. In real applications, however, not every operation should run immediately. Sending an email one day after registration, generating a report every night, or publishing a notification after data synchronization has completed requires scheduling and workflow dependencies.

In this lesson, we will implement three Hangfire scenarios: a delayed job, which runs after a specified time; a recurring job, which runs repeatedly according to a Cron expression; and a continuation job, which starts after another job has completed successfully. We will use an order system to build a workflow for report generation, temporary-data cleanup, and notifying users when a report is ready.

Hangfire stores job definitions in persistent storage. Therefore, a scheduled job is not simply lost from memory when the application restarts. However, a running Hangfire Server and an available application process are still required to schedule and process jobs on time.

1. Scheduling a future operation with a delayed job

A delayed job is not placed in the processing queue immediately. Hangfire stores it as scheduled work and moves it to a queue when its scheduled time arrives. The main API for this scenario is BackgroundJob.Schedule.

public sealed class NotificationJobs
{
    private readonly INotificationService _notifications;

    public NotificationJobs(INotificationService notifications)
    {
        _notifications = notifications;
    }

    public async Task SendWelcomeNotificationAsync(int userId)
    {
        await _notifications.SendWelcomeAsync(userId);
    }
}

After creating a user, we can schedule the notification for one day later:

[HttpPost("users")]
public IActionResult CreateUser(CreateUserRequest request)
{
    var userId = _userService.Create(request);

    var jobId = BackgroundJob.Schedule(
        jobs => jobs.SendWelcomeNotificationAsync(userId),
        TimeSpan.FromDays(1));

    return Accepted(new { userId, jobId });
}

The API request does not wait for the notification to be delivered. The Schedule call stores the job definition and returns its identifier. It is important to pass only userId as the job argument. Passing a user object, email body, or large report model directly can increase storage size and cause stale data to be used later. Reading current data from the database when the job executes is usually safer.

Using an exact date and time

You can provide an exact date instead of a relative delay. Producing the date in UTC and expressing the business rule explicitly reduces dependence on the server's local clock.

var runAtUtc = DateTimeOffset.UtcNow.AddHours(2);

var jobId = BackgroundJob.Schedule(
    jobs => jobs.GenerateOrderReportAsync(reportId),
    runAtUtc);

Delayed jobs are not guaranteed to start with exact second-level precision. The Hangfire Server checks scheduled jobs at intervals, so a job may start shortly after its target time. If the business deadline is critical, the job should verify the current state and the allowed delay before performing its work.

2. Creating periodic tasks with recurring jobs

A recurring job is a single job definition that is triggered repeatedly. RecurringJob.AddOrUpdate creates or updates a record with the specified identifier. This feature is useful for daily reports, hourly synchronization, cleanup operations, and periodic health checks.

public sealed class MaintenanceJobs
{
    private readonly IOrderRepository _orders;
    private readonly ILogger<MaintenanceJobs> _logger;

    public MaintenanceJobs(
        IOrderRepository orders,
        ILogger<MaintenanceJobs> logger)
    {
        _orders = orders;
        _logger = logger;
    }

    public async Task DeleteExpiredReservationsAsync()
    {
        var deletedCount = await _orders.DeleteExpiredReservationsAsync();
        _logger.LogInformation(
            "{Count} expired reservations deleted.", deletedCount);
    }
}

We can register the recurring job when the application starts:

RecurringJob.AddOrUpdate<MaintenanceJobs>(
    "orders:delete-expired-reservations",
    jobs => jobs.DeleteExpiredReservationsAsync(),
    Cron.Hourly());

The identifier is important. Use a stable and unique identifier instead of generating a random value at every application startup. Registering the same identifier again updates the existing schedule rather than creating a duplicate. Reusing one identifier for different jobs can cause one definition to overwrite another.

Cron expressions

Hangfire's Cron helper provides readable expressions for common schedules:

ScenarioExample
Every hourCron.Hourly()
Every dayCron.Daily()
Every weekCron.Weekly()
Every monthCron.Monthly()
Advanced rule"0 2 * * *"

For example, a daily report can use a Cron expression for approximately 02:00 UTC. But for jobs that must follow a user's local time, relying only on the Cron expression is insufficient; the timezone should also be specified.

3. Running according to local time zones

The rule “every day at 09:00” is ambiguous unless the timezone is defined. A container or Linux host may use a different system timezone than the developer's computer. Therefore, define the timezone as application configuration and pass it explicitly through the recurring job options.

var timezoneId = configuration["Jobs:Timezone"] ?? "Europe/Istanbul";
var timezone = TimeZoneInfo.FindSystemTimeZoneById(timezoneId);

RecurringJob.AddOrUpdate<ReportJobs>(
    "reports:daily-order-summary",
    jobs => jobs.GenerateDailyOrderSummaryAsync(),
    "0 9 * * *",
    new RecurringJobOptions
    {
        TimeZone = timezone
    });

Timezone identifiers differ between operating systems. Windows may expose identifiers such as “Turkey Standard Time”, while Linux and macOS commonly use IANA identifiers such as Europe/Istanbul. Make sure the required timezone data exists in the Docker image. In production, read the identifier from configuration rather than hard-coding it, and fail with a clear startup error when the configured identifier is invalid.

TimeZoneInfo.FindSystemTimeZoneById can throw when an identifier cannot be found. For a more defensive approach, use TryFindSystemTimeZoneById. Regions with daylight-saving changes also require special tests because some local times can be skipped or occur twice.

4. Building workflows with continuation jobs

A continuation job depends on the completion of an antecedent job. The most common design is to continue only when the previous job succeeds. For example, we can generate a report first and then email the report link.

var reportJobId = BackgroundJob.Enqueue<ReportJobs>(
    jobs => jobs.GenerateMonthlyReportAsync(reportId));

var notificationJobId = BackgroundJob.ContinueJobWith<NotificationJobs>(
    reportJobId,
    jobs => jobs.SendReportReadyNotificationAsync(reportId),
    JobContinuationOptions.OnlyOnSucceededState);

If the first job fails, the continuation does not run by default. The first job may be retried by Hangfire; once it reaches the succeeded state, the continuation is placed into a queue. This is safer than calling two unrelated background jobs because the dependency and its condition are persisted in storage and visible in the job workflow.

Instead of depending directly on the return value of the antecedent job, pass the identifier of a shared database record to the continuation. Job expressions are serialized, so local variables, HttpContext, the current user, or an open database connection are not automatically carried into the background process.

Handling the failure path

If an administrator must be notified after report generation fails, use a separate failure-notification job or monitoring system. Keep the main continuation tied only to successful completion. This produces a clearer workflow and avoids accidentally treating a failed job as successful.

public async Task GenerateMonthlyReportAsync(int reportId)
{
    var report = await _reports.LoadAsync(reportId);

    try
    {
        await _reportGenerator.GenerateAsync(report);
        await _reports.MarkCompletedAsync(reportId);
    }
    catch (Exception exception)
    {
        await _reports.MarkFailedAsync(reportId, exception.Message);
        throw;
    }
}

Rethrowing the exception is important. If the exception is swallowed, Hangfire may mark the job as successful and execute a success-based continuation.

5. Combining a complete workflow

In the following scenario, a user requests a report, the report is scheduled five minutes in the future, and a notification is sent after successful completion:

[HttpPost("reports")]
public IActionResult CreateReport(CreateReportRequest request)
{
    var reportId = _reportService.CreatePending(request);

    var generationJobId = BackgroundJob.Schedule<ReportJobs>(
        jobs => jobs.GenerateAsync(reportId),
        TimeSpan.FromMinutes(5));

    var notificationJobId = BackgroundJob.ContinueJobWith<NotificationJobs>(
        generationJobId,
        jobs => jobs.SendReportReadyAsync(reportId),
        JobContinuationOptions.OnlyOnSucceededState);

    return Accepted(new
    {
        reportId,
        generationJobId,
        notificationJobId
    });
}

The API only schedules the workflow. The report status can be tracked in the database as Pending, Completed, or Failed. In many APIs, returning the report identifier is more useful to clients than exposing a Hangfire job identifier; job identifiers can still be kept in logs and operational screens.

6. Testing and verification

  1. Use a short delay such as TimeSpan.FromMinutes(1) when testing delayed jobs.
  2. Use Cron.Minutely() temporarily to verify a recurring job, then restore the production schedule.
  3. Add structured logs to the job method and verify the report state in the database.
  4. Use the Hangfire Dashboard to inspect Scheduled, Enqueued, Processing, Succeeded, and Failed states.
  5. Restart the application after scheduling a job and confirm that it continues from persistent storage.
  6. Throw a controlled exception in the antecedent job and verify that the success continuation does not run.
  7. Change the timezone configuration and test whether the expected local execution time is preserved.

Common mistakes

  • Assuming the application is a scheduler: A recurring job cannot be triggered if the Hangfire Server is not running.
  • Mixing local time and UTC: Define dates and configuration explicitly as UTC or with a named timezone.
  • Ignoring idempotency: A recurring job may generate the same report twice. Use a business key, state check, or unique database constraint.
  • Passing large objects as arguments: Pass identifiers and load the current data when the job executes.
  • Swallowing exceptions: Log the failure and rethrow the exception so Hangfire does not mark the job as successful.
  • Registering recurring jobs with random identifiers: Use a stable identifier so startup registration updates one job instead of creating many.
  • Expecting exact execution time: Small delays caused by polling, system load, and worker capacity are normal.

Short practice exercise

Create a “nightly maintenance workflow.” First, define CleanupJobs.RemoveExpiredFilesAsync and register it as a recurring job for 02:30 every day. Then accept a data-export request through an API, schedule the export as a delayed job ten minutes in the future, and attach NotificationJobs.SendExportReadyAsync as a continuation that runs only after successful completion.

During testing, answer these questions: Does the job survive an application restart? Does the 02:30 expectation remain correct after changing the timezone? Is the notification skipped when the export fails? Does starting the application twice leave one recurring-job record rather than duplicates?

Conclusion

Delayed jobs are suitable for one-time future operations, recurring jobs for regular maintenance and reporting, and continuation jobs for dependent workflows. A reliable design separates scheduling from business logic, defines the timezone explicitly, keeps job arguments small, and makes every job safe to run more than once.

In the next lesson, we will examine Hangfire exception handling, automatic retries, rerun strategies, and operational monitoring in more detail.

Sources