Why will this timer not start in a .net service application?

17,178

Solution 1

This helps for me.

Imports System
Imports System.Timers

Public Class MyTimers

    Protected Overrides Sub OnStart(ByVal args() As String)

        Dim MyTimer As New System.Timers.Timer()
        AddHandler MyTimer.Elapsed, AddressOf OnTimedEvent

        ' Set the Interval to 10 seconds (10000 milliseconds).
        MyTimer.Interval = 10000
        MyTimer.Enabled = True
    End Sub

    Private Shared Sub OnTimedEvent(source As Object, e As ElapsedEventArgs)
        Console.WriteLine("Hello World!")
    End Sub
End Class

Solution 2

If you are using System.Windows.Forms.Timer that won't work in a service. Look into the other two times you can use in .NET.

Solution 3

You need to bind your events properly. You can use System.Timers.Timer and bind the Elapsed event to tmrRun_Tick before you start the timer.

This article explains the different timers.

Share:
17,178
kevin bailey
Author by

kevin bailey

Updated on June 04, 2022

Comments

  • kevin bailey
    kevin bailey almost 2 years

    I have this code for a Windows service I am writing in .NET....However the TICK function never gets executed regardless of what interval I put in the tmrRun properties. What am I missing? I am sure its something stupid I am not seeing.

    Thank You

        
    Imports System.IO
    
    Public Class HealthMonitor
    
        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.
            tmrRun.Start()
        End Sub
    
        Protected Overrides Sub OnStop()
            // Add code here to perform any tear-down necessary to stop your service.
            tmrRun.Stop()
        End Sub
    
        Private Sub tmrRun_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles tmrRun.Tick
            //DO some stuff
        End Sub
    End Class
    
    
  • Jacob Siemaszko
    Jacob Siemaszko over 10 years
    Thank you this helped me too :) Great!