LeSabo
LeSabo

Reputation: 47

Loop to check time in VB.NET

So I'm kind of new to VB and am just playing around with a little project, I currently need a loop that is constantly checking the systems clock to see if it's equal to a certain time.

   While Not myTime.Hour = 24

        If TimeOfDay = newTime Then
            nfi.ShowBalloonTip(15)
            intRandNumb = RandomNumber(1, 15)
            dblAddMinutes = intTime + intRandNumb
            newTime = TimeOfDay.AddMinutes(dblAddMinutes)

        End If
    End While

I have this right now, but obviously it's grinding everything to a halt and using 50% of my cpu in the process, I just would like to know what I can substitute in or change to make this loop run better and perform how I need it to.

Upvotes: 0

Views: 5551

Answers (4)

o.k.w
o.k.w

Reputation: 25790

As Joel pointed out, you should try using a timer instead. I'm not sure if your app is a form or console or other, so I'll try to be generic and use System.Timers.Timer.

The code here (interval is set at 10ms, change to a value of your need):

Private timer1 As System.Timers.Timer    
Const interval As Integer = 10 


Sub initTimer()
    timer1 = New System.Timers.Timer(10)
    AddHandler timer1.Elapsed, AddressOf Me.timer_Elapsed
    timer1.Start()
End Sub

Sub timer_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs)
    'do your stuff here
    'Console.WriteLine(e.SignalTime.ToString())
End Sub

Upvotes: 0

Joel Coehoorn
Joel Coehoorn

Reputation: 415690

checking the systems clock to see if it's equal to a certain time.

There are two "correct" ways to do this:

  1. Build a normal app that doesn't care what time it is, and set it up in windows as a schedule task.
  2. Check the time once and calculate how long until the desired time. Then set up a timer to wait for that exact duration.

Under no circumstance should you keep polling the system clock for something like this that will just run once.

Upvotes: 1

Grizzly
Grizzly

Reputation: 20191

You can use

Threading.Thread.Sleep(0)

This will cause the working thread to yield the rest of it's current timeslice which will reduce the cpu usage quite a bit. However you should consider whether you really nead busy waiting for the time or if you could get away with setting a timer to count down the difference between the current time and the expected time, e.g.:

            var t = new System.Timers.Timer((DateTime.Now - DateTime.Now).TotalMilliseconds);
        t.Elapsed = DoSomething;
        t.Start();

Upvotes: 1

Amirshk
Amirshk

Reputation: 8258

you can add

Threading.Thread.Sleep(0),

this will cause a context switch and greatly reduce the CPU usage

Also consider using a timer object to be called every 10 or 100 ms, this will also be better in usage then having a loop

Upvotes: 1

Related Questions