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:

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

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();
}

We also need to add namespaces:

And the last step, create a database. Go to SSMS and execute the command:
CREATE DATABASE [HangfireTest]
GO

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.


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.

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”