In this video, we are delving into the vast
world of Hangfire, where a single tool can do more than just triggering background
jobs. Let's discover how hangfire can save you time, boost productivity, and make your
applications more powerful than ever before. I have just created a dotnet core Web API project
to demonstrate, how to use Hangfire. But the great thing about hangfire is that, you can use it in
different types of dotnet core applications, such as MVC, Blazor or even console applications. It's
a versatile tool that can be applied in various scenarios to make your job easier. The initial
step is to install the Hangfire library from Nuget Packages. Now, let's go ahead and search
for hangfire in the package manager. Right at the top of the list you can see the Hanngire
Library. I'll go ahead and install it. We have the option to designate a specific database for
hangfire to store job details. There are various database choices available for hangfire, and I'll
be showing you the details shortly. At the moment, I am configuring it to use a SQL Server database.
Before we dive into development, let me share a few important details with you. I have brought
up the hangfire website here and you can find the website URL in the video description below. If
we navigate to the overview page and take a look at the left side menu, you'll notice an option
called extensions. Within this section you will find a comprehensive list of extensions that can
be seamlessly integrated with Hangfire. Scrolling down you will come across a dedicated storage
section. These extensions come in handy when you want to explore storage options beyond SQL Server.
As you can see, the listing includes options like Azure Cosmos DB, Firebase, MongoDB, MySQL, PostgreSQL
and more. To use these storage alternatives, you can simply install the respective libraries
from Nuget packages, giving you the flexibility to choose your preferred storage method. Before
we proceed with our development, I would like to introduce you to a reliable hosting provider
called hostinger. If you are in the market for VPS hosting to host your applications, hostinger is a
top-notch choice you should definitely explore. I have included my affiliate link in the video
description below. Feel free to check out the exclusive offers they provide and it's a great
way to support this channel while getting top quality Hosting Services. Alright, let's kick start
our development process. To begin we'll start by adding the necessary dependencies. We can easily
incorporate Hanngfire into a project by utilizing the "AddHangfire" method to add the service.
We'll also need to configure a few settings within these configurations. We'll start by adding
a connection string for our data database. Let's begin by adding this connection string to our
"appsettings.json" file. I have named it DB connection. As you can see, I've specified the database name as
hangfire_demo. Set the UserID as "sa" and included the password. Next, we'll retrieve
this connection string from the configuration file. Then I'll make a call to the use SQL Server
storage method passing the connection string as a parameter. In addition, we must ensure that the hangfire
server is added to our dependency services. We can achieve this by simply invoking the "AddHangfireServer"
method. Now let's run the application and I'll demonstrate an error that we are likely
to encounter. As you can see, we are receiving an error message that says "Cannot Open Database".
This issue arises because we haven't created the database yet. So the hangfire server is unable
to establish a connection. Let's resolve this by creating the database. I am simply copying the
database name from our appsettings.json file. Now using the SQL Server Management Studio, we
can proceed to create the database. With the database successfully created, you will notice
that there are currently no tables present. I'll go ahead and run the application once more. As
you can see there are no errors this time. Now, let's switch over to SQL Management Studio
and refresh the tables. You can now see that hangfire has automatically generated some
tables. These tables will be used to store job information and its associated details. Next,
I'll illustrate how we can create various types of jobs in Hangfire. To do this I am going to
set up an API controller called JobController. Now let's delve into creating our first type of
job the background job. A background job can be used for performing resource intensive tasks such
as email delivery, file transfer operations, data import or export processes, or any operation
requiring dedicated time and resources. All seamlessly executed in the background. I'll go
ahead and create this method. This method will return an OK response. To create a background
job, we'll make use of the BackgroundJob.Enqueue method. We can pass the action we want to trigger
as a parameter. In this example, we'll simply write a message to the console window which will say
background job triggered. Let's see this in action. I'll run the application. As you can see, we have
the console window on the left and the Swagger page on the right. Using swagger, I'll call this API
method. Almost immediately after executing, you can observe that the action is triggered. I'll execute
the method once more and you can see the message displayed in the console window again. Next, let's
explore how to perform a scheduled job. I'm adding a new method inside our controller named create
scheduled job. Similar to the previous method, this one also returns an OK response. First, we'll
create a date-time object to specify when we want to schedule the job. In this case, let's schedule
it to run 5 seconds after triggering this method. We can create a date-time offset object based on
our date-time object. To schedule the job, we'll use the "BackgroundJob.Schedule" method. It
takes two parameters, the action to be triggered and the date-time offset. I'll run the project and
schedule a job. Let me execute the new method from Swagger. As you can see, I have executed the API
method and now the job will be triggered within 5 Seconds. We can observe the job's output in the
console window. I'll execute the method once more to demonstrate that the job is indeed executed as
scheduled. I hope this clarifies how to schedule a job for a specific date and time. Now, let's dive
into creating a continuation job. A continuation job is a job that executes immediately after
another job has completed. As you can see, the "BackgroundJob.Schedule" method is returning
a string. This returned string is actually the Job ID of the scheduled job. Similarly, "BackgroundJob.Enqueue"
also returns a Job ID. In this new method, I am scheduling a job just as we did before and
storing the Job ID in a variable. Then I am creating a continuation job using the "BackgroundJob.ContinueJobWith"
method. For the first parameter, we pass the parent Job's ID which is the Job ID
of the scheduled job. Next, we specify the action to be triggered in this continuation job. In this
case, I am writing a "Continuation Job 1 Triggered" message to the console window. Keep in mind that
even this continuation job returns a Job ID. We can create additional continuation jobs as well. Let's
get the Job ID of this continuation job and use it to create another continuation job that should
trigger upon completion of this one. We'll do the same for one more continuation job. Now let's
run the application and see how it all works. I'll call the API method. The first scheduled job will
trigger after 5 seconds and the continuation jobs will follow one by one. As you can see, all the jobs
are triggered sequentially. Moving on, let's create a new API method for recurring jobs which happen
to be one of the most commonly used job types in hangfire. With recurring jobs, you can repeatedly
run a job at a specific time intervals. To create a recurring job, we'll utilize the "RecurringJob.AddOrUpdate"
method. The first parameter we need to pass is an ID for this job. If there is already
another recurring job with the same ID, it will be updated. Next, we specify the action to be triggered
and finally we provide a cron expression. There are various online tools available for generating
Cron Expressions, tailored to your needs. Personally I often use ChatGPT for generating
hangfire cron expressions. For instance if you want a job to run every one minute, you can
simply ask ChatGPT to create a hangfire cron expression for that. Here is a cron expression
generated by ChatGPT for running a task every minute. If you need the job to run every 5 minutes
instead, you can request a different expression. We can use this expression for triggering the job
in every 5 minutes. For our example, let's use the cron expression for running the job every
minute. I'll run the application and put it to the test. Let's trigger the Recurring Job API. Now as it
might take a bit of time, I'll fast forward through the video. I've waited for 3 minutes and you can
see that the job was executed three times. Exactly as scheduled. Moving forward, let's explore how to
leverage injected dependencies while executing the jobs. I'll start by creating a folder named jobs.
Inside this folder, I'll create a class named test job. In this class, I am making use of ILogger which
is a default injected dependency in dotnet core. To access this dependency, we can simply retrieve
it from the class Constructor and assign it to a read-only object. Within this class, I have added
a method named WriteLog. This method is designed to log a message passed as a parameter, along with the
current date and time. Now, let's explore how to call this method from Hangfire jobs. We'll need to
make a few small changes to our current approach. First, when using the "BackgroundJob.Enqueue" method,
we need to specify the class name as well. Then we can assign the method to be called using a lambda
expression. We can apply the same approach to the "Background.Schedule" job method as well.
I'll make these modifications to all the jobs in our CreateContinuationJob API method. Likewise, we
can also adjust the recurring job accordingly. Now, let's run the project and see how it all works in
action. We'll begin with CreateBackgroundJob. As you can observe, the log message is being displayed.
Next, let's try the CreateScheduleJob method. It should trigger after 5 Seconds. Now let's check
the continuation job. Finally, let's examine the recurring job. I'll fast forward through the video
again as it might take some time. As you can see, everything is working perfectly fine. All the jobs
are executing as expected. Next, I'll demonstrate how to enable the Hangfire dashboard. The hangfire
dashboard allows us to view the details of our jobs. To enable it, we can use the "app.UseHangfireDashboard"
method. I'll run the application now and I'll show you how the dashboard looks. To
access the dashboard, you can simply add hangfire to our application's URL. Here you can see
various values, a real-time graph, and a history graph on the hangfire dashboard. Within the jobs
section you can view the jobs categorized by their status. Let's take a look at the succeeded jobs.
By clicking on a specific job, you can access more details such as latency, duration and more. Since
we have a recurring job scheduled, you can observe it in the real-time graph when it's triggered.
If you click on the recurring jobs option, you can access the details related to recurring
jobs. This includes information like the cron expression, next execution, last execution and more.
Clicking on the last execution allows you to delve deeper into the execution details. We also have
the option to customize the Hangfire dashboard further by providing parameters to the
"app.UseHangfireDashboard" method. For instance you can specify a custom path with which the dashboard can
be accessed. In this example, we have set a custom path and now you can access the dashboard using
only the path we have specified. We can further fine tune the Hanngfire dashboard by providing
a dashboard option object as a parameter. In this example, we have set a custom title for
the dashboard and disabled the dark mode by setting "DarkModeEnabled" to false. Now, let's take
a look at the dashboard. As you can see, the title we assigned is displayed on the top left and dark
mode is disabled. In the footer bar you might have noticed, it's displaying the database name. If you
want to hide this, you can simply set the "DisplayStorageConnectionString" property to false. As a
result, it's no longer displayed in the footer. We can enhance the security of the dashboard by
enabling authentication. In this example, I'll demonstrate how to enable basic authentication. To
get started, we need to install the "Hangfire.Dashboard.Basic.Authentication" library from nuget
packages. Once installed, we can use the "HangfireCustomBasicAuthenticationFilter" object to
specify a username and password for authentication. I'll run the application now to demonstrate
how it works. As you can see, when we access the dashboard URL, it now prompts us for credentials.
You can only access the dashboard by providing the assigned username and the password. In this
tutorial, we have uncovered the power of Hangfire from scheduling background and recurring
jobs to customizing your hangfire dashboard. With these skills, you can supercharge
your .NET Core applications. Don't forget to like, share and subscribe for more valuable
insights. Thanks for watching and Happy Coding!