In this article I will explain how to
create a Windows Service in Asp.Net.
Firstly you have to add a new project
of type Windows Service with name 'MyFirstWindowService' as shown below.
First of all we need to add Quartz.Net
reference from NuGet package Manager for that Gotop
Toolsè
from NuGet package ManagerèManage
NuGet Packages For Solution
A window will open. Search for
Quartz.Net, Install and add it to your project.
Now add following Namespaces to your
project
using Quartz;
using Quartz.Impl;
using Quartz.Impl.Triggers;
Now copy and Paste the
Below code
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
private static IScheduler _scheduler;
private const string Job = "Job";
private const string Group1 = "MyGroup";
protected override void OnStart(string[] args)
{
ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
_scheduler = schedulerFactory.GetScheduler();
_scheduler.Start();
Jobs();
}
protected override void OnStop()
{
}
public static void Jobs()
{
try
{
const string trigger1 = "MyFirstWindowServiceTrigger";
const string jobName = trigger1 + Job;
IDoJob myJob = new FirstWindowServices();
var jobDetail = new JobDetailImpl(jobName, Group1, myJob.GetType());
var trigger = new CronTriggerImpl(
trigger1,
Group1,
"0 0/1 * 1/1 * ? *" /* run every minute */ ) { TimeZone = TimeZoneInfo.Utc };
_scheduler.ScheduleJob(jobDetail, trigger);
var nextFireTime = trigger.GetNextFireTimeUtc();
}
catch (Exception er)
{
}
}
internal interface IDoJob : IJob
{
}
internal class FirstWindowServices : IDoJob
{
public void ProcessUsersFirstWindowService()
{
string path = "C:\\ServiceLog.txt";
using (StreamWriter writer = new StreamWriter(path, true))
{
writer.WriteLine("Window Service started at " +DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt"));
writer.Close();
}
}
public void Execute(IJobExecutionContext context)
{
ProcessUsersFirstWindowService();
}
}
}
Now you can install window
service. To know how to install window service go to the following link.
http://keepsharingkeeplearning.blogspot.in/2016/05/how-to-installuninstall-window-service.html
You can also test window
service on console application for that you need to add a method given to your
service.
/// <summary>
/// Method to test Window service
/// </summary>
/// <param name="args"></param>
internal void TestStartupAndStop(string[] args)
{
this.OnStart(args);
Console.ReadLine();
this.OnStop();
}
Now Replace Main function
in Program.cs file with code given belew
Build and run
static void Main(string[] args)
{
if (Environment.UserInteractive)
{
Service1 service = new Service1();
service.TestStartupAndStop(args);
}
}
No comments:
Post a Comment