Pages

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"

   


8. Add key in AppSettings section of app.config which will hold the Cron Expression
    
        
    

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:


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.