Timer stops working after sometime in windows service

808 views Asked by At

I have a windows service that runs every one minute and performs some DB and IO operations.

Everything works fine but I have observed that after some time service does not work.

It shows started but nothing is happening.

1) Can this be bcoz of timer being collected by GC? If yes then whats wrong with my code.

2) I have used timer.enable in onstart and onstop, should i use timer.start and timer.stop.

3) If I want to user Threading.Timer then what all do I need to change in the following code.

Any help will be appreciated

Imports System.ServiceProcess
Imports System.Timers
Imports System.Configuration

Public Class ReportingImmediate
    Inherits ServiceBase

#Region "Members"

    Private ReadOnly time As Timers.Timer
    Private ReadOnly ReportingHelper As ReportingHelper
    Private ReadOnly timeInterval As String

#End Region

    Public Sub New()
        ' Initialize Logs
        InitializeComponent()
        ' Initialize other components
        time = New System.Timers.Timer()
        timeInterval = ConfigurationManager.AppSettings("ImmediateReRunInterval")
        time.Interval = Integer.Parse(timeInterval)
        AddHandler time.Elapsed, AddressOf TimeElapsed
        objReportingHelper = New ReportingHelper()

    End Sub

#Region "Timer Event"

    ''' <summary>time Elapsed</summary>
    ''' <param name="sender">The object that raised the event sender</param>
    ''' <param name="e">Event data passed to the handler e</param>
    Private Sub TimeElapsed(sender As Object, e As ElapsedEventArgs)
        time.Enabled = False
        objReportingHelper.GetReportsForExecutions(1)
        ' Enable the Timer
        time.Enabled = True
        time.Interval = Integer.Parse(timeInterval)
    End Sub

#End Region

#Region "Service Events"

    ''' <summary>On Start</summary>
    ''' <param name="args">Arguments</param>
    Protected Overrides Sub OnStart(args As String())
        time.Enabled = True
    End Sub

    ''' <summary>On Stop</summary>
    Protected Overrides Sub OnStop()
        time.Enabled = False
    End Sub

#End Region

End Class
0

There are 0 answers