Newbie: How to keep program running

  • Thread starter Thread starter Harold Paine
  • Start date Start date
H

Harold Paine

Ok, this may sound silly, but what's the best way to keep a program running?
For example, say I wanted to msgbox the date every 10 minutes.

I have just a simple module, no forms.

Sub Main()
Msgbox ( Now() )
End Sub

Even if I add a timer, it runs through the code once and ends. (I've left
out the timer declaration and event handler to show msgbox)

Sub Main()
myTimer.Interval = 10000
myTimer.Enabled = True
End Sub

So I put a simple "While" loop in to keep it running with a Thread.sleep to
keep the CPU usage down.

Sub Main()
myTimer.Interval = 10000
myTimer.Enabled = True
While myTimer.Enabled = True
System.Threading.Thread.Sleep(100)
End While
End Sub

So, my question: Is this how it's done? Is there a proper way? Why even
use the timer - Couldn't I just sleep the thread for the 10 seconds, and
then run the event again?

Thanks for the help
HP
 
Thanks. Would anything be different if this was run as a service?

For posterity the end result of my sample looks like this:

Private WithEvents myTimer As Timers.Timer = New Timers.Timer
Sub Main()
myTimer.Interval = 10000
myTimer.Enabled = True
Application.Run()
MsgBox("Goodbye")
End Sub

Private Sub myTimer_Elapsed(ByVal sender As System.Object, ByVal e As
System.Timers.ElapsedEventArgs) Handles myTimer.Elapsed
Dim response As MsgBoxResult
response = MsgBox(Now(), MsgBoxStyle.OKCancel, "HP")
If response = MsgBoxResult.Cancel Then
myTimer.Enabled = False
Application.Exit()
End If
End Sub

I don't have any forms so I just use Application.Run() and not
Application.Run(Form)
I notice any code I put after Appliction.Run() is not run until the
Application.Exit() is called. The MsgBox("Goodbye") is called after the
Application.Exit();

-Thanks
HP
 
Back
Top