Background Task Scheduling with Hangfire

juarezasjunior

Juarez Júnior

Posted on October 26, 2024

Background Task Scheduling with Hangfire

Hangfire is a library for .NET that simplifies running background tasks and scheduling jobs. It allows you to schedule recurring tasks or perform long-running operations outside the main application flow, without the need to write complex code to manage threads or processes. In this example, we will see how to configure Hangfire to run a background task and schedule a recurring task.

Libraries:

To use the Hangfire library, install the following NuGet packages in your project:

Install-Package Hangfire
Install-Package Hangfire.MemoryStorage
Enter fullscreen mode Exit fullscreen mode

Example Code:

using Hangfire;
using Hangfire.MemoryStorage;
using System;
using System.Threading.Tasks;

class Program
{
    static void Main(string[] args)
    {
        // Configuring Hangfire with in-memory storage
        GlobalConfiguration.Configuration.UseMemoryStorage();

        using (var server = new BackgroundJobServer())
        {
            // Scheduling a job for immediate execution
            BackgroundJob.Enqueue(() => BackgroundTask());

            // Scheduling a recurring job (executed every minute)
            RecurringJob.AddOrUpdate("recurring-task", () => RecurringTask(), Cron.Minutely);

            Console.WriteLine("Jobs scheduled. Press Enter to exit...");
            Console.ReadLine();
        }
    }

    // Task that will run in the background
    public static void BackgroundTask()
    {
        Console.WriteLine("Background task executed.");
    }

    // Recurring task
    public static void RecurringTask()
    {
        Console.WriteLine("Recurring task executed.");
    }
}
Enter fullscreen mode Exit fullscreen mode

Code Explanation:

In this example, we configure Hangfire to use in-memory storage (using the Hangfire.MemoryStorage package) and initialize the background job server. We use the BackgroundJob.Enqueue method to schedule the immediate execution of a task called BackgroundTask. Additionally, we use RecurringJob.AddOrUpdate to schedule a recurring task (RecurringTask), which will be executed every minute. The code stays in a loop, waiting for the user to press Enter to exit the application.

Conclusion:

Hangfire is a simple and powerful solution for managing background and scheduled tasks in .NET applications. It abstracts the complexity of working directly with threads or timers, providing an easy-to-use API for scheduling jobs efficiently.

Source code: GitHub

💖 💪 🙅 🚩
juarezasjunior
Juarez Júnior

Posted on October 26, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related