Hangfire – create fire-and-forget, delayed and recurring tasks.

This time I want to show you how easy is to set up and use Hangfire a .Net tool to create fire-and-forget, delayed and recurring tasks.

In their words: “Hangfire allows you to kick off method calls outside of the request processing pipeline in a very easy, but reliable way. These method invocations are performed in a background thread and called background jobs.”

Hangfire Workflow

 

Suppose you have a heavy  process and you don’t need the result right away to continue or your process needs to trigger a background task, in this case Hangfire is really useful because you can schedule this process as a new job to be treated by a Hangfire server later. The first advantage I want to highlight is that we don’t need to take care about the scheduler we just need start the server and in our client en-queue the jobs so lets see how easy is configure and run the server.

Configure Hangfire server

Because Hangfire can run in any owin application I’ve created a console application to host the Hangfire server. As you can see in the code below we just call the static method Start in the class WebApp and start the server.

static void Main(string[] args)
{
   using (WebApp.Start<Startup>("http://localhost:8888"))
   {
      Console.ReadKey();
   }
}

Now we have the server running so lets see how to configure it. As you can see we need to let Hangfire know the connection string where the server will pickup the tasks. I didn’t tell you but Hangfire only requires an empty database. The first time the server runs will take care and creates the needed tables. Then you can see I’m using two methods (only one is required)  one to start the server and the other one to let Hangfire know that we want a dashboard.

public class Startup
{
   public void Configuration(IAppBuilder app)
   {
      GlobalConfiguration.Configuration.UseSqlServerStorage("connection_string");
      app.UseHangfireServer();
      app.UseHangfireDashboard();
   }
}

Using the server

We already have the server up and running. Now it’s time to en-queue the tasks. I’ll create two different tasks one to add a recurring task schedule to run every minute and another just to en-queue a task that will run only once.

static void Main(string[] args)
{
   using (WebApp.Start<Startup>("http://localhost:8888"))
   {
      Console.WriteLine("Server started... press ENTER to shut down");
      RecurringJob.AddOrUpdate(() => Job("This is a recurring job: "), Cron.Minutely);
      BackgroundJob.Enqueue(() => Job("This is an enqueue job"));
      Console.ReadKey();
   }
}

public static void Job(string msg)
{
   Console.WriteLine(msg);
}

And this is it. You can see a basic configuration and use of Hangfire is really easy. As I said at the beginning this is a really powerful tool and a good solution for recurring task or background jobs. There are much more advanced configuration that I’ll try to cover in a later post.