Creating Windows services in VB.Net, Scheduling tasks with Window Services and Timer

Windows services, formerly known as NT services enable you to create long-running executable applications that run in its own Windows session, which then has the ability to start automatically when the computer boots and also can be manually paused, stopped or even restarted.

Window Services do not have any interface to the user.
Before Microsoft.Net Framework introduced windows services are developed by using C or C++ languages. To create windows services using C or C++, you need to have good programming skills in those languages.

But, after introducing Microsoft .Net Framework, you can easily create window services with minimum programming skills. In this article I will explain how to create windows service by using VB.Net.

To Create window Services, Open Visual studio -->FileNew-->Project

Select Visual Basics from left side, windows service from right side and name the project as TimerWindowService as shown below.

Window Services

Here I want to log some information for every second. For this I am using file streams and timer control. To write code, right click on Design window and select view code.
Import required namespace for this.

Imports System.IO
Imports System.Timers

To save information I wrote the one method. This method will save the information to a notepad file. The code for this look like below.


Public Sub SaveLog(ByVal strData As String, ByVal FullPath As String) Try Dim fs As New FileStream("C:\log.txt", FileMode.OpenOrCreate, FileAccess.Write) Dim sw As New StreamWriter(fs) sw.BaseStream.Seek(0, SeekOrigin.End) sw.WriteLine(strData) sw.Flush() sw.Close() Catch Ex As Exception End Try End Sub

This method will create the new file in C drive with name “log”, if it is not there. Then it writes all data to that file which is supplied for this method.

We have Timer Control in .Net Framework, but it may not function correctly for windows Services. So, here I am using Timer Object.

Declare object for Timer class in the class

Dim timer As New Timer()

Then We have to define OnElapsedTime method for Timer control to write log to file. The code look like below.

    
Protected Sub OnElapsedTime(ByVal source As Object, ByVal e As ElapsedEventArgs) SaveLog("processing at " & DateTime.Now.ToString, "C:\log.txt") End Sub

Now we have to write code for the OnStart method of the windows service.


Protected Overrides Sub OnStart(ByVal args() As String) SaveLog("statrting at " & DateTime.Now.ToString, "C:\log.txt") AddHandler timer.Elapsed, AddressOf OnElapsedTime timer.Interval = 1000 timer.Enabled = True End Sub

In first line of method we are writing some text to Log, second line we are handling OnElapsedTime event handler and for the next lines we are defining time interval for the Timer control and we are enabling Timer control. Here we areging time interval as 1000 milli seconds i.e, 1 second.

After that we have to define code for OnStop method of window services.

    
Protected Overrides Sub OnStop() timer.Enabled = False SaveLog("Stopping Service at " & DateTime.Now.ToString, "C:\log.txt") End Sub

In the OnStop method, we are just diabling the Timer control and we are writing some message to Log regarding stopping service.

OnStart and OnStop methods are executed when ever the window service is started and window service stopped.

Stll now, we write the code for windows service. Now we have to install window service. For that we have to add installer for this service like below.


Window Services

Then you can get the new ProjectInstaller form with ServiceInstaller1 and ServiceProcessInstaller1 elements.

Right click on ServiceInstaller1, select properties and set the DisplayName, ServiceName as TimerService which was displayed on the services panel and you can find StartType as Manual(by default).

After that Right Click on ServiceProcessInstaller1, select properties and set account to LocalSystem.

Now Build the total project, then you get the exe file for this window service. We have to place this exe file in GAC(Global Assembly Cache).
For this got to Visual Studio Tools and select Command prompt, enter following command.

installutil –i D:\projects\TimerWindowService\bin\Debug\TimerWindowService.exe

Press enter, then you get the “The Commit phase completed successful” and “The transacted install has completed.” Messages.

So, your services successfully added to the system services. Now you have to activate the service.
Go to Administrative Tools, select Services then you get the all available services tab in the window. Go to TimerService service, right click on this service and select start as shown below.
If you do not find the TimerService, just refresh all services.

Window Services

Then you can find messages regarding starting service, processing in the log.txt file in the C drive.

Go to Services and right click on TimerService , select stop. Now you can find stopping the service in log.txt.

To Uninstall the service go to visualstudio tools and select command prompt, enter following command. Then your service will uninstall.

installutil –u D:\projects\TimerWindowService\bin\Debug\TimerWindowService.exe

In this way you can create your own windows service easily. If you want to write messages to Database table instead of file you can.


Download source code here