1. Introduction
If you want to schedule something to run or your program takes long time to process, Sometimes we may have to create a separate service application,
Windows service allows a long running application to run in a own windows process. These services can be managed thorough a services portal available in Windows. A service can be started, stopped, paused or restarted by automatically as well as manually.
I wanted to write an application to send emails in specific time periods, I thought of writing a windows service application.
We can install this service in your server or local computer and configure it to run on intervals using a timer.
2. Create a Windows service
When we create a windows service from visual studio, It gives us a service class with constructor method, OnStart and OnStop methods as follows.
public
Scheduler()
{
}
protected
override
void
OnStart(
string
[] args)
{
}
protected
override
void
OnStop()
{
}
2.1. Scheduling the task with a timer
When program needs to periodically perform a task, for that it needs a timer component, add a timer into the service design from toolbox
2.2. Fill up OnStart method
we need to initialize timer component inside the OnStart method, then I set timer interval and added a elapsed event to track each interval.
protected
override
void
OnStart(
string
[] args)
{
Debugger.Launch();
logger.Info(
"Service is started."
);
try
{
Timer tmrEmailScheduler =
new
Timer();
tmrEmailScheduler.Interval = 120000;
tmrEmailScheduler.Elapsed += tmrEmailScheduler_Elapsed;
tmrEmailScheduler.Start();
ProcessEmail.CreateEmail();
}
catch
(Exception ex)
{
logger.Error(ExceptionHandler.ToLongString(ex));
}
}
2.3. Actual scheduling done in here
inside timer elapsed event, actual task is going to run. elapsed event is called for each 2 minutes according to this code sample
private
void
tmrEmailScheduler_Elapsed(
object
sender, ElapsedEventArgs e)
{
logger.Info(
"Timer is ticked"
);
ProcessEmail.CreateEmail();
}
2.4. How to stop the execution
to stop the execution, OnStop event is used.
protected
override
void
OnStop()
{
logger.Info(
"Service is stopped."
);
tmrEmailScheduler.Stop();
}
3. How to install the windows service
Before installing the service in your pc, we need to create a installer class,
Add installer class as shown above
3.1. Installer Class
In Installer class, we need to give a service name, so we can identify the service by its name.
[RunInstaller(
true
)]
public
partial
class
ProjectInstaller : System.Configuration.Install.Installer
{
private
ServiceProcessInstaller process;
private
ServiceInstaller service;
public
ProjectInstaller()
{
InitializeComponent();
process =
new
ServiceProcessInstaller();
process.Account = ServiceAccount.LocalSystem;
service =
new
ServiceInstaller();
service.ServiceName =
"test Service"
;
Installers.Add(process);
Installers.Add(service);
}
}
3.2. Let’s install the service
service is getting created after we build the application. we can find the .exe file in the bin folder. But we can’t install the service by double clicking on it.
we have to install it to the local pc or server.
3.3. InstallUtil
InstallUtil.exe is used to install/uninstall services in local machine or server. We can run installUtil command from Developer command prompt, type InstallUtil.exe with full path to the service exe file.
But this doesn’t going to install the service, It throws an error.
It seems like we don’t have access to install the service, Let's try this, run Developer command prompt as administrator, then this permission issue is getting resolved.
We can install a service using cmd as well,
run cmd as administrator, then we can install the service using cmd as well.
4. View services
We can check available services, by just typing services in your program list.
I gave service name as ‘test service’ in installer class.
5. Windows service on Local Computer started and then stopped
I tried to start the service from the panel, But it didn't work,
this issue comes normally when code has some kind of a error. It’s somewhat difficult to debug a windows service application to find out errors,
6. Debug a windows service application
normally in a windows service, program.cs looks like this.
If we want to check whether our service implementation has any issue, we can use this trick
manually start a method that has exact same code as the service implementation, inside of start method implementation, we can check whether service logic works properly.
using this trick, we can identify our service logic is working fine.
Another way of testing the program logic is, create another console application and call service logic method from console app and verify it works fine.
6.1. Debugger Launch
If we want to debug onStart method, we can launch the debugger in start method
we can launch the debugger like this,
we can debug the code like this.
But in here specific file we attached into debugger is getting loaded. So other files are not loaded. Only we can debug the service file as this code sample shows.
7. Windows service can’t connect to the database
In my service, i need to access to the database, But it gives me an error like this, Login failed. Login failed for user ‘NT AUTHORITY\SYSTEM’
windows service is running on ‘NT AUTHORITY\SYSTEM’ login. this login doesn’t seem to have access to the database.
To resolve this, add this in your connectionstring, Integrated Security=SSPI or else create a user account for ‘NT AUTHORITY\SYSTEM’ in your database server and give necessary permissions.
8. Downloads
8.1. TechNet Gallery
- You can find the code sample from https://gallery.technet.microsoft.com/Create-a-simple-smtp-email-5a1656b1
8.2. Github
- You can check the github repo from, https://github.com/hansamaligamage/Scheduler
9. Conclusion
This article explains how to configure a windows service to send emails periodically. If you go through the code sample, We have used a timer component to handle the timeline, Windows service is running accordingly in its own process without being idle until it stops.
No comments:
Post a Comment