Click here to Skip to main content
15,897,518 members
Articles / Programming Languages / Visual Basic

How to Create a Simple Polling Service

Rate me:
Please Sign up or sign in to vote.
4.13/5 (46 votes)
15 Jan 2007CPOL6 min read 274.8K   5.6K   121  
An article to quickly and easily setup a polling service, i.e., a task that runs by itself in the background and periodically does something.
Imports System.Threading

Public Class PollingService
    ' Keep track of worker thread.
    Private m_oPollingThread As New Thread( _
        New System.Threading.ThreadStart(AddressOf PollProcess))

    Protected Overrides Sub OnStart(ByVal args() As String)
        ' Add code here to start your service. This method should set things
        ' in motion so your service can do its work.
        EventLog1.WriteEntry("PollingService is starting.")

        ' Start the thread.
        m_oPollingThread.Start()
    End Sub

    Protected Overrides Sub OnStop()
        ' Add code here to perform any tear-down necessary to stop your service.
        EventLog1.WriteEntry("PollingService is stopping.")

        ' Stop the thread.
        m_oPollingThread.Abort()
    End Sub

    Private Sub PollProcess()
        ' Loops, until killed by OnStop.
        EventLog1.WriteEntry("PollingService service polling thread started.")
        Do
            ' Wait...
            System.Threading.Thread.Sleep(30000) ' 30000 = 30 seconds

            PollingPass()
        Loop
    End Sub

    Private Sub PollingPass()
        Try
            ' Do Stuff Here...
            EventLog1.WriteEntry("PollingService service polling pass executed.")
        Catch ex As System.Exception
            EventLog1.WriteEntry("PollingService encountered an error '" & _
                ex.Message & "'", EventLogEntryType.Error)
            EventLog1.WriteEntry("PollingService service Stack Trace: " & _
                ex.StackTrace, EventLogEntryType.Error)
        End Try
    End Sub

End Class

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
Canada Canada
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions