C# Creating Scheduled Tasks with Hangfire

Hello, C# developers! In today’s post, we’re diving into Hangfire, a popular library for creating background jobs in C#. Hangfire provides a simple way to run background tasks guaranteed to be executed, ensuring that your application can handle tasks like sending emails or processing data without blocking operations. Let’s explore how to set up Hangfire and create scheduled tasks in your applications.

What is Hangfire?

Hangfire is an open-source library that allows you to easily create, process, and manage background jobs in .NET applications. With its simple API and powerful dashboard, Hangfire makes it easy to schedule tasks, run recurring jobs, and handle long-running processes without requiring additional configuration.

Setting Up Hangfire in Your Application

To get started, create a new ASP.NET Core Web Application:

dotnet new webapp -n HangfireDemo
cd HangfireDemo

Next, install the Hangfire package from NuGet:

dotnet add package Hangfire

Configuring Hangfire

You need to configure Hangfire in your application. Open the Startup.cs file and add the following code to configure Hangfire services and middleware:

using Hangfire;

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // Configure Hangfire to use an in-memory storage (for testing)
        services.AddHangfire(configuration => configuration.UseInMemoryStorage());
        services.AddHangfireServer();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // Enable Hangfire dashboard at /hangfire
        app.UseHangfireDashboard();
        app.UseRouting();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
        });
    }
}

This configuration sets up Hangfire to use in-memory storage, which is convenient for development and testing purposes. The dashboard will be accessible at /hangfire.

Creating a Background Job

Now, let’s create a simple background job that sends a message. In your project, you can add a new class to handle jobs:

public class BackgroundJobs
{
    public static void SendMessage()
    {
        Console.WriteLine($"Message sent at {DateTime.Now}");
    }
}

This method simulates sending a message with a timestamp when invoked.

Scheduling the Job

You can schedule the job to run immediately or as a recurring task. Here’s how you can schedule a background job in the Main method or any place where you have access to the IBackgroundJobClient:

public class Program
{
    public static void Main(string[] args)
    {
        // Run the web application and background job service
        CreateHostBuilder(args).Build().Run();

        // Schedule a recurring job
        RecurringJob.AddOrUpdate<BackgroundJobs>("SendMessageJob", job => job.SendMessage(), Cron.MinuteInterval(1));
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

This will set up a job to run the SendMessage method every minute.

Accessing the Hangfire Dashboard

To view your background jobs, run your application and navigate to /hangfire in your web browser. You’ll see the Hangfire dashboard, where you can monitor running jobs, scheduled jobs, and their statuses.

Best Practices for Using Hangfire

  • Use Persistent Storage: For production, configure Hangfire to use a persistent storage option (like SQL Server or Redis) to maintain job data across application restarts.
  • Implement Retry Logic: Hangfire automatically retries failed jobs based on configurable retry policies, but handle exceptions in your job methods for better reliability.
  • Define Job History: Keep track of job executions and outcomes for debugging and monitoring purpose.

Conclusion

Using Hangfire in your C# applications allows you to effectively manage background tasks and processes. By implementing periodic jobs and utilizing the user-friendly dashboard, you can enhance your applications with robust scheduling features. Start using Hangfire today to automate and manage background work seamlessly!

To learn more about ITER Academy, visit our website. Visit Here

Scroll to Top