Saturday, August 3, 2019

Scheduling Tasks In ASP.NET With Quartz.Net

1) Install Quartz.Net using the Nuget Package manager.



2) Create a job which you would call upon to do your work. In next step this job will be called when the job starts its cycle.

    public class IsosJob : IJob
    {
        public void Execute(IJobExecutionContext context)
        {
            XmlDocument isosResult = new XmlDocument();
            isosResult.Load("http://path to get my xml content file");
            string path = "C:\\temp\\doc\\test.xml";
            XmlTextWriter writer = new XmlTextWriter(path, null);
        }
    }

3)  Creating a trigger and scheduling a job

using Quartz;
using Quartz.Impl;

namespace TestWeb.Jobs
{
    public class JobScheduler
    {
        public static void Start()
        {
            IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();
            scheduler.Start();

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

            ITrigger trigger = TriggerBuilder.Create()
                .WithDailyTimeIntervalSchedule(s => s.WithIntervalInMinutes(2)
                .OnEveryDay()
                .StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(14, 24))
             )
             .Build();

            scheduler.ScheduleJob(job, trigger);
        }
    }
}

4) Start the job

The best place to start the job is inside the Application_Start method in the global.asax file. The job will also start with along with other bootstrapping functions start.

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

            JobScheduler.Start();
        }

Using this approach is good when you don't have access to various scheduling options in the server such as task scheduler or a window service. In those scenarios this comes in handy. That said, there are limitations in using web based approaches to carry on scheduled tasks unlike using windows services or a worker. For an instance, if the app pool gets recycled while the job is running the state of the application is not saved and information loss may happen.

1 comment: