Hi, look into codes below:

Sub Main()        
        Dim tmr As New Timers.Timer

        tmr.Interval = TimeSpan.FromMinutes(5).TotalMilliseconds
        tmr.Start()
          
        'Do function
        
End Sub

As my program above, i set the time interval to every 5 minute which it will do the function. However, after 5 minites it does not affect any thing in my program, is that my coding wrong? or I had miss something? (I am using console application)

Where is your other code - the code you want to run when the timer ticks?

Are you means the codes of the function?

the function is ok, just when I put the timer, my timer does not take effect. It just straight do the function and didn't wait for the time interval as expected (5 minit)

I now using a new way as below:

Sub Main()
        Dim aTimer As New System.Timers.Timer()
        AddHandler aTimer.Elapsed, AddressOf DoFunction
        aTimer.Interval = 1000           
        aTimer.Enabled = True

    End Sub

 Public Sub DoFunction(ByVal source As Object, ByVal e As ElapsedEventArgs)
' Do function

End Sub
End Module

When I debug, I found that the program just ran till the first "End Sub" at line 7 and after that it dont have go further to DoFunction method, why would like that? How to call the DoFunction inside the Main method?

Hi

Sorry for the late reply. Ok I just noticed you said this is a console application which means that when it gets to line 7 then it will just end.

You need to keep the app alive. Windows forms apps are kept alive for you but console apps will just die unless you tell them otherwise.

You can do this by putting a Console.Read() after line 5 or better still an endless loop. In a real app you would give a way of exiting the loop but for brevity this will do:

Imports System.Timers

Module Module1

    Sub Main()
        Dim aTimer As New System.Timers.Timer()
        AddHandler aTimer.Elapsed, AddressOf DoFunction
        aTimer.Interval = 2000
        aTimer.Enabled = True
        'aTimer.Start()

        While True

        End While
    End Sub

    Public Sub DoFunction(ByVal source As Object, ByVal e As ElapsedEventArgs)
        Console.WriteLine("Do Work")
    End Sub

End Module

Thanks for the reply, but I am sorry because the requirement had been changed, now the function is still same, but the timer need to put at service, is that the syntax or coding of the timer in window service application is same as console application?

Yes its pretty much the same - just make sure you keep the service alive!

Thanks DavaAmour for the help:)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.