Click here to Skip to main content
15,897,273 members
Articles / Web Development / ASP.NET
Tip/Trick

How To Create Scheduled Background Task (ASP.NET)

Rate me:
Please Sign up or sign in to vote.
4.69/5 (8 votes)
17 Jul 2015CPOL2 min read 33.3K   26   4
How to create background task in ASP.NET web appliccation via Quartz.net

Introduction

I’m writing now to share my experience in Quartz.net. With this library, you will be able to build background task in your web application.

Background

This tip is intended for developers who are familiar with the .NET Framework and develop their web applications using ASP.NET.

Imagine that you want to:

  • Send newsletter for members every day, week, or fortnight
  • Send some reminders by email at specific time, so what should you do?
  • Clear some temporary folder in regular period

Indeed, you should use one of the two strategies to implement that:

  • Host Windows service in your IIS in a traditional way.
  • Build your service programmatically and let it start when your application started.

In my opinion, the second strategy is not more efficient than the first only, but more portable as well.

Keep in your mind, the better you implement it, the more quality you will get, below you can find the major steps to do that in the simplest way.

Using the Code

Firstly, you should install Quartz library via NuGet manager.

Image 1

Secondly, you should implement IJob interface which has one method to be overridden and do your stuff inside.

C#
public class YourJob : IJob
    {
        public void Execute (IJobExecutionContext context)
        {
            /*
             * Do stuff here, send reminder or emails.
             */            
        }
    }

Then, you should build trigger to run the previous code in each regular period as follows:

C#
public class SomeScheduler
    {
        public static void Start()
        {
            IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();
            scheduler.Start();

            IJobDetail job = JobBuilder.Create<YourJob>().Build();

            ITrigger trigger = TriggerBuilder.Create()
                .WithDailyTimeIntervalSchedule
                  (s =>
                     s.WithIntervalInHours(24)
                    //s.WithIntervalInSeconds(20)
                    .OnEveryDay()
                    .StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(0, 0))
                  )
                .Build();

            scheduler.ScheduleJob(job, trigger);
        }
    }

s.WithIntervalInHours(24) means that YourJob.Execute(); will trigger every hour.

Finally, you can start your background task at the start of application.

Suppose we develop an ASP.NET web application, so we can call start in Application_Start method in Global.asax.

C#
protected void Application_Start()
{
SomeScheduler.Start();
}

So, we can summarize the process by these steps:

  • Install Quartz from NuGet manager.
  • Build YourJob class.
  • Build your scheduler.
  • Start your task at the start of your application.

I hope that I present a useful way to implement your background task in the simplest way.

Please don’t hesitate to ask me for any further assistance.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Turkey Turkey
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionAfter deploying how to achieve keep these services running all life long Pin
Member 128824039-May-17 0:43
Member 128824039-May-17 0:43 
QuestionRun only once Pin
billle10-Aug-16 20:56
billle10-Aug-16 20:56 
Questionweekly task Pin
heresanjay019-Aug-15 21:52
heresanjay019-Aug-15 21:52 
SuggestionCan you document a little more? Pin
AndyHo20-Jul-15 5:20
professionalAndyHo20-Jul-15 5:20 
Hello, the library sounds appealling, but it lacks information on if it has permanent storage or not, for example if you use it inside IIS, the whole IIS shuts down all applications priosdically (in a regular basis), and you can do very little from within your .net app to avoid this; so, any scheduling system who appreciates and can fire a process in, lets say 24 hours, should store 'the schedule' in a sort of 'permanent' storage (SQL, xml, file, etc.), or it will never know when to fire ¿does it?
Also if you give you example as a webapp, sometimes a webapp is somehow handicapped for async operations like this, it simply cannot interact easily with a web client, because he might not be online, just when the event fires. So unless the event do some homework, sends a message to the user in any other protocol, an asynch one, the task is useless for webapps.
Its unclear form me all of this uses, and digging in your source code is not my prefferred style, sorry!
¿can you explain a little more?
It will be appreciated!
best regards! Wink | ;)

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.