Skip to main content

Hangfire with ASP.Net MVC : Simplest Code To Start with

It seems many are looking for using Hangfire with ASP.Net MVC 4 / 5+ SQL Server here is the simplest code example for you to start quick.

I am using Visual Studio 2017 Community Edition

1) Create ASP.Net MVC 4/5 Projects
2) <add key="owin:AutomaticAppStartup" value="false" /> in web.config file
3)Run Install-Package HangFire -Version 1.6.17 or visit here for latest version: https://www.nuget.org/packages/Hangfire/1.6.17
4) From the sample code, make sure you create database in SQL Server DB and update the connection string.
5) I am simply updating a table with a primary key (auto incremented), and string field "StampTime" with current date and time.
6) Open Global.asax.cs and put this code.
7) Run the app and check the database.

The example code also showcase a hack on how to run jobs with few seconds interval.


namespace HangFireDemo
{
    public static class MyTasks
    {
        public static async Task<int> MinuteTick()
        {
            await Task.Run(() =>
            {
                BackgroundJob.Schedule(() => MyTasks.Tick(), TimeSpan.FromSeconds(15));
                BackgroundJob.Schedule(() => MyTasks.Tick(), TimeSpan.FromSeconds(30));
                BackgroundJob.Schedule(() => MyTasks.Tick(), TimeSpan.FromSeconds(45));
                BackgroundJob.Schedule(() => MyTasks.Tick(), TimeSpan.FromSeconds(59));
            });

            return 1;
        }

        public static async Task<int> Tick()
        {
            await Task.Run(() =>
            {
                using (HangFireDemo.Models.HangFireDBEntities db = new Models.HangFireDBEntities())
                {
                    db.Tracks.Add(new Models.Track
                    { StampTime = DateTime.Now.ToString("dd-MMM-yyyy hh:mm:ss tt") });
                    db.SaveChanges();

                }
            });

            
            return 1;

        }
    }

    public class MvcApplication : System.Web.HttpApplication
    {
        private BackgroundJobServer _backgroundJobServer;

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);


            GlobalConfiguration.Configuration
               .UseSqlServerStorage(@"Server=.\sqlexpress2012; Database = hangfiredb; User Id = sa;Password = system456*;");

            _backgroundJobServer = new BackgroundJobServer();

            RecurringJob.AddOrUpdate(() => MyTasks.MinuteTick(), Cron.Minutely);
        }
        protected void Application_End(object sender, EventArgs e)
        {
            _backgroundJobServer.Dispose();
        }
    }
}

If you really want to witness documentation that looks super good and tells you too many things that you feel not-required at the beginning, read the Hangfires official long startup guide: http://docs.hangfire.io/en/latest/tutorials/send-email.html.

Please note, this is just a quick get-start sample code for learning and may not be production ready.

Also check my followup post: Hangfire with In-Memory Storage (ASP.Net MVC 4/5) 


Comments

Popular posts from this blog

How a university is saving 2.5 tons of paper every year?

Considering the current environmental imbalances, many non-profit organizations (like The Nature Conservity , SayTree …and many others) around the world working desperately to save plant  and trees. It is our responsibility too. We felt starting with universities is the better place to spread the awareness. With this, we also made universities administrative work more manageable and effective. The story I am going to share tells you how a university quietly worked and stands as a role model by saving tons of paper and millions of rupees of its own and its students. In the year 2012, VT University (Visvesvaraya Technological University also popularly known as “ VTU ”) Belgavi (India), has moved its thesis evaluations to online to effectively reduce its use of paper and streamline the process online. University’s this decision made it save several Lakhs of rupees (~ tens of thousands of dollars) every year in paper cost while giving faculty and administrators more direct a...

Why Akbar was Great?

I have fanatical interest to be acquainted with what made Indian emperors take influential decisions during their reign. Few great kings’ valuable decisions created a remarkable history. When Akbar accepts the marriage proposal of Hindu King (Bharmal of Amer), he wishes to make an attempt to set an example for two culture and religions and convey the message of peace. Later, destiny takes him to the critical path of life having most depraved political and family oriented problems. Being a true great emperor, Akbar learns and conclude challenges by demonstrating his exceptional leadership qualities. With his verdicts, Akbar stands as an incomparable king of all time. “Jodha Akbar” – brings 16th-century incidents to life and shows beginning part of Akbar’s married life which was, in fact, a deal for political gain. This decision slowly unleashes Akbar’s loving life, internal dreadful politics, painfully desirous people around him and betraying family members. Jalaluddin Mohamma...

Linux - My Second Attempt

First time when I tried installing Linux on my box, I was failed to appraise it. I concluded that “I am typical ‘Windows’ user and might be not-understanding the Linux way”. I took break; I read some good articles on Linux. Few articles mentioned like “This Linux distribution is so easy that my grandma can use it…” I downloaded few Linux distributions (I would prefer not to mention their names here.) and tried installing one by one on my laptop. In almost all distributions, my first impression of Linux being faster operating system was gone. When I wanted to install new utility software (.rpm package) I had to learn command prompt options and finally ended up with error messages which tells one or the other supporting library is missing. Badly organized start menu always took more than required time to find out what I wanted. Too many small utilities fail to achieve user needs as a whole. Few distributions were good in few things. My overall intention was to get faster Linux on my ...