Oct 17, 2014

How to implment CRON job in windows service using C#

In this post we will go throught the steps involved in creating a windows service which will repeat according to specified CRON EXPRESSION


1. Create a windows Service named "CronService"



2. Right click on the project in solution explorer, click on "Manage NuGet Packages"



 

3. Search for "Quartz.NET" and click on "Install" to install the package


 

4. Create a interface called "ITaskScheduler"


public interface ITaskScheduler
{
 string Name { get; }
 void Run();
 void Stop();
}
 
5. Create a class "TestTask" which inherits from "IJob" (IJob is an interface provided by quartz.net, you need to import the "Quartz" namespace in this class)

 
public class TestTask : IJob
{
 public void Execute(IJobExecutionContext context)
 {
  //Your main code goes here
  //WRITE YOUR CODE HERE
 }
}

6. Right click on the project in solution explorer, click on "Add Reference", select "System.Configuration" from .NET tab 



7. Add "TaskScheduler" class which will implement the above created interface "ITaskScheduler"

   
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Quartz;
using Quartz.Impl;
using System.Configuration;

namespace CronService
{
    public class TaskScheduler : ITaskScheduler
    {
        private IScheduler _scheduler;
        public string Name
        {
            get { return GetType().Name; }
        }

        public void Run()
        {
            ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
            _scheduler = schedulerFactory.GetScheduler();

            string taskGroup = "Test Group";
            string taskName = "Test Name";

            IJobDetail testJob = JobBuilder.Create<testtask>()
                    .WithIdentity(taskName, taskGroup)
                    .Build();

            ITrigger testTrigger = TriggerBuilder.Create()
                    .WithIdentity(taskName, taskGroup)
                    .StartNow()
                    .WithCronSchedule(ConfigurationManager.AppSettings["Interval"])
                    .Build();

            var dictionary = new Dictionary<IJobDetail, Quartz.Collection.ISet<itrigger>>();
            //var dictionary = new Dictionary<IJobDetail, Quartz.Collection.ISet<itrigger>>();

            dictionary.Add(testJob, new Quartz.Collection.HashSet<itrigger>()
                                {
                                    testTrigger
                                });


            _scheduler.ScheduleJobs(dictionary, false);
            _scheduler.Start();
        }

        public void Stop()
        {
            _scheduler.Shutdown();
        }
    }
}

8. Add key in AppSettings section of app.config which will hold the Cron Expression
    
<appsettings>
        <add key="Interval" value="0 0/15 * 1/1 * ? *" />
</appsettings>

The current cron expression "0 0/15 * 1/1 * ? *" means that the service will run every 15 minutes.
Format of the cron expression is: [Minutes] [Hours] [Day of month] [Month] [Day of week] [Year]
You can get more information about cron expression from following page:
Cron Expression

You can obtain cron expression for your own schedule from following website:
www.cronmaker.com

Finally in your service's main class you need to write following code:
 
public partial class Service1 : ServiceBase
{
 ITaskScheduler scheduler;
 public Service1()
 {
  InitializeComponent();
 }

 protected override void OnStart(string[] args)
 {
  scheduler = new TaskScheduler();
  scheduler.Run();
 }

 protected override void OnStop()
 {
  if (scheduler != null)
  {
   scheduler.Stop();
  }
 }
} 

Please note that you need to write your code in the "TestTask" class's 'Execute' method and not in 'OnStart' method of your windows service.

Want to implement CRON in your C# project?
I would love to connect with you on a short Skype Call to understand project requirements and how I can help.

No comments:

Post a Comment

Be the first to comment on this post.