C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
And: We use the method TimerElapsed (you can name it whatever you like) to run when the interval is reached.
SignalTime: The ElapsedEventArgs gives us access to SignalTime, which is a DateTime. It is the time the Timer was fired.
DateTimeVB.NET program that uses Timer
Imports System.Timers
Module Module1
Sub Main()
Dim timer As Timer = New Timer(200)
AddHandler timer.Elapsed, New ElapsedEventHandler(AddressOf TimerElapsed)
timer.Start()
' Wait and run the timer.
Console.Read()
End Sub
Sub TimerElapsed(ByVal sender As Object, ByVal e As ElapsedEventArgs)
' Write the SignalTime.
Dim time As DateTime = e.SignalTime
Console.WriteLine("TIME: " + time)
End Sub
End Module
Output
TIME: 4/3/2019 2:49:43 PM
TIME: 4/3/2019 2:49:43 PM
TIME: 4/3/2019 2:49:44 PM
TIME: 4/3/2019 2:49:44 PM
TIME: 4/3/2019 2:49:44 PM
TIME: 4/3/2019 2:49:44 PM
TIME: 4/3/2019 2:49:44 PM
TIME: 4/3/2019 2:49:45 PM
Next: We call the AddHandler operator to assign the Handler subroutine as the code that is executed every 3 seconds.
Finally: We set the Enabled property to True to start the Timer. It begins measuring time elapsed.
Class that uses Timer type: VB.NET
Imports Microsoft.VisualBasic
Imports System.Timers
Public Class TimerTest
Shared _timer As Timer
Shared _list As List(Of String) = New List(Of String)
''' <summary>
''' Start the timer.
''' </summary>
Shared Sub Start()
_timer = New Timer(3000)
AddHandler _timer.Elapsed, New ElapsedEventHandler(AddressOf Handler)
_timer.Enabled = True
End Sub
''' <summary>
''' Get timer output.
''' </summary>
Shared Function GetOutput() As String
Return String.Join("<br>", _list)
End Function
''' <summary>
''' Timer event handler.
''' </summary>
Shared Sub Handler(ByVal sender As Object, ByVal e As ElapsedEventArgs)
_list.Add(DateTime.Now.ToString())
End Sub
End Class
And: The GetOutput() Function will show the DateTimes that were collected by the Timer.
Then: In the Application_BeginRequest subroutine, we output the text of the List collected by the Timer.
Example Global.asax: VB.NET
<%@ Application Language="VB" %>
<script runat="server">
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
TimerTest.Start()
End Sub
Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
Response.Write(TimerTest.GetOutput())
End Sub
</script>
Tip: Refresh the page occasionally and you will see the Timer is executing its Handler code.
Default.aspx: If you are starting with an empty ASP.NET website, you will want to add a Default.aspx page as well.
Info: Default.aspx will trigger the runtime to call the Application_Start and Application_BeginRequest handlers.