Background automation tasks in .NET Core – sample console application using Hangfire

I will show a simple console application using Hangfire to automate tasks.

First, create a new project: Console App (.NET Core). In my case netcoreapp3.1:

Create a new project

Install Hangfire – add packages:
Hangfire.Core
Hangfire.SqlServer

Add Hangfire packages

Copy the following code to the Main method:

GlobalConfiguration.Configuration
    .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
    .UseColouredConsoleLogProvider()
    .UseSimpleAssemblyNameTypeSerializer()
    .UseRecommendedSerializerSettings()
    .UseSqlServerStorage("Data Source=(LocalDb)\\MSSQLLocalDB; Database=HangfireTest; Integrated Security=True;", new SqlServerStorageOptions
    {
        CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
        SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
        QueuePollInterval = TimeSpan.Zero,
        UseRecommendedIsolationLevel = true,
        UsePageLocksOnDequeue = true,
        DisableGlobalLocks = true
    });

BackgroundJob.Enqueue(() => Console.WriteLine("Hello, world!"));

using (var server = new BackgroundJobServer())
{
    Console.ReadLine();
}
Main method with sample code

We also need to add namespaces:

Add namespaces

And the last step, create a database. Go to SSMS and execute the command:

CREATE DATABASE [HangfireTest]
GO
Create a database in SSMS

You need to take attention on connection string in .UseSqlServerStorage. Put appropriate data source for your local database and appropriate database name, same like created in sql command to create database.

My connection string:

"Data Source=(LocalDb)\MSSQLLocalDB; Database=HangfireTest; Integrated Security=True;"

Now we can run our application.

We can see that for now we have one task that writes on the screen: “Hello, world!”.
Database tables have also been created that store all data related to Hangfire.

Hangfire – console app
Hangfire database with tables

Now we can try to add one more task that run recurring job. Just add these lines of code:

RecurringJob.AddOrUpdate(
        () => Console.WriteLine("Recurring job!"),
    Cron.Minutely);

And every minute it displays: “Recurring job!”. We can configure the time period in the Cron expression, in this sample it is Cron.Minutely.

RecurringJob

We can also use cron expressions to specify a more complex schedule. For example, run every 15th minute:

RecurringJob.AddOrUpdate("id-job2",
        () => Console.WriteLine("Recurring job2"),
    "*/15 * * * *");

Cron expression that I used: “*/15 * * * *”, I like this site for generating cron expressions:
https://crontab.guru

Also, I had to add a recurring job id in method AddOrUpdate: “id-job2”, because identifiers should be unique for each recurring job.

And that’s it, I recommend this documentation for Hangfire:
https://docs.hangfire.io/en/latest/

For ASP.NET Core applications:
https://docs.hangfire.io/en/latest/getting-started/aspnet-core-applications.html

Hangfire home page:
https://www.hangfire.io

In the next blog post, I will show a simple Hangfire test application but in ASP.NET Core and with a nice dashboard to monitor tasks and e.g. how to call a controller method with Hangfire.

One thought on “Background automation tasks in .NET Core – sample console application using Hangfire

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: