How to use a timer in a console application with VB.NET

2 Answers

0 votes
' General-purpose timers in console apps

Imports System
Imports System.Timers

Module Program

    Private timer As Timer

    Sub Main()
        timer = New Timer(1000) ' 1 second
        AddHandler timer.Elapsed, AddressOf TimerElapsed
        timer.AutoReset = True
        timer.Enabled = True

        Console.WriteLine("Timer started. Press Enter to exit.")
        Console.ReadLine()
    End Sub

    Private Sub TimerElapsed(sender As Object, e As ElapsedEventArgs)
        Console.WriteLine("Tick: " & DateTime.Now)
    End Sub

End Module

 
 
' run:
'
' Timer started. Press Enter to exit.
' Tick: 4/13/2026 9:18:46 AM
' Tick: 4/13/2026 9:18:47 AM
' Tick: 4/13/2026 9:18:48 AM
' Tick: 4/13/2026 9:18:49 AM
' Tick: 4/13/2026 9:18:50 AM
' Tick: 4/13/2026 9:18:51 AM
'


 



answered Apr 13 by avibootz
edited Apr 13 by avibootz
0 votes
' High-performance background tasks

Imports System
Imports System.Threading

Module Program

    Private timer As Timer

    Sub Main()
        ' Start immediately (dueTime:=0), tick every 1000 ms
        timer = New Timer(AddressOf Tick, Nothing, 0, 1000)

        Console.WriteLine("Timer started. Press Enter to exit.")
        Console.ReadLine()
    End Sub

    Private Sub Tick(state As Object)
        Console.WriteLine("Tick: " & DateTime.Now)
    End Sub

End Module

 
 
' run:
'
' Timer started. Press Enter to exit.
' Tick: 4/13/2026 9:26:07 AM
' Tick: 4/13/2026 9:26:08 AM
' Tick: 4/13/2026 9:26:09 AM
' Tick: 4/13/2026 9:26:10 AM
' Tick: 4/13/2026 9:26:11 AM
' Tick: 4/13/2026 9:26:12 AM
'



answered Apr 13 by avibootz

Related questions

...