65.9K
CodeProject is changing. Read more.
Home

Scheduling tasks with VB.NET as Windows services

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.17/5 (15 votes)

May 5, 2005

1 min read

viewsIcon

158593

downloadIcon

5227

An article on Windows services using VB.NET.

Introduction

After the introduction of .NET, writing services using VB.NET has become very simple and easy. But still beginners need a start from somewhere to know how to achieve this. Attached is a sample application which demonstrates this concept.

Background

This is a slightly modified version of the article submitted by Xiangyang Liu, to create a simple Windows service using VB.NET. Thanks to Xiangyang Liu, for the code that I have used to build Windows services in .NET. This code explains some additional things like, XML file reading, database and stored procedure handling etc.. I have simplified the code to make it simple to understand for the beginners.

Using the code

For those who know a bit of .NET applications, this code is pretty simple. To install and test this application, please modify the application path within the Installservice.bat which exists in the bin folder.

//
serviceInstaller -i NotificationService 
  D:\Training\WindowsService\Shanservice\ 
  NotificationService\bin\NotificationService.exe
ServiceInstaller -r NotificationService
//

If the path is correct in the installservice.bat, then the new service called NotificationService will be installed and started within the Service Control Manager.

The class NotificationService is inherited from System.ServiceProcess.ServiceBase. It will run the code only once, when the user logs in for the first time or when the service is started. But if you want the action to keep happening depending upon a trigger you need to use the timer calls from the system. Please also note that, the Timer event calls the subroutine which sends an email. I have set it to fire the event every two seconds. You can change this if you want to. I have used my personal email ID here. Please change it before you test the code or I will be getting millions of emails.

''
Protected Overrides Sub OnStart(ByVal args() As String)
        Try
            t = New Timer(2000)
            AddHandler t.Elapsed, AddressOf TimerFired
            With t
                .AutoReset = True
                .Enabled = True
                .Start()
            End With
        Catch obug As Exception
            LogEvent(obug.Message)
            Throw obug
        End Try
    End Sub

 Protected Overrides Sub OnStop()
  Try
  log.WriteEntry("Service Stopping", EventLogEntryType.Information)
  t.Stop()
  t.Dispose()
  Catch obug As Exception
  LogEvent(obug.Message)
  End Try
  End Sub

Private Sub TimerFired(ByVal sender As Object, ByVal e As ElapsedEventArgs)
  Working()
End Sub
''