Ehsan Ghanbari

Experience, DotNet, Solutions

Delayed jobs in Hangfire

Hangfire is a job scheduling framework which provides background processing without needing any windows service. That's the main point and competitive advantage of Hangfire in compare to other similar libraries. Imagine sending a million of message or email in your application, you don't need to force the user to wait for all the processes to be completed. Despite, there are lots of ways to accomplish the mentioned job; Hangfire uses the request processing pipeline of ASP.Net for processing and executing jobs however it runs in every framework of Microsoft!

In order to create delayed jobs, just call the BackgroundJob.Schedule(). Create a console application and install the library from nuget  and call Schedule(,) :

            BackgroundJob.Schedule(

                () => Console.WriteLine("Job Scheduled!"),

                TimeSpan.FromDays(5));

The above code simply will be scheduled the job from 5 days later. You can also run the task in a specific date like this:

   BackgroundJob.Schedule(

             () => Console.WriteLine("Job Scheduled!"),

             new DateTime(2017, 02, 05, 12, 00, 00));

Not that the default time of enqueueing the scheduled jobs by hangfire server is 15 seconds which is changeable. To change that default periodical schedule, initiate the BackgroundJobServerOptions in the constructor:

 var options = new BackgroundJobServerOptions

{

    SchedulePollingInterval = TimeSpan.FromMinutes(5)

};

var server = new BackgroundJobServer(options);

HangFire Server is responsible for background job processing. To start the background processing, create an instance of  BackgroundJobServer and start it.       

        var server = new BackgroundJobServer(options);           

        server.Start();

At the time of writing this post, the start() of BackgroundJobServer() is obsolete! You don't have to call start, it will be started automatically by the constructor. Call dispose() to waiting for server shutdown:

server.Dispose();

 



About Me

Ehsan Ghanbari

Hi! my name is Ehsan. I'm a developer, passionate technologist, and fan of clean code. I'm interested in enterprise and large-scale applications architecture and design patterns. I spend a lot of time on software architecture. Since 2008, I've been as a developer for different companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the past years, Read More

Post Tags
Pending Blog Posts
using Elmah in asp.net MVC4
Using FluentSecurity in MVC
Strategic design
Factory Pattern
time out pattern in ajax
Redis as a cache server
How to use PagedList In asp.net MVC
Multiple submit buttons in asp.net MVC
Domain driven design VS model driven architecture
What's the DDD-lite?