Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call a function every x minutes in VB.NET?

Tags:

vb.net

How do I call a function every x minutes.

I assume I'd have to add a timer to the form?

like image 324
bear Avatar asked Jan 11 '12 01:01

bear


2 Answers

here is a simple example:

Public Class SampleCallEveryXMinute

     Private WithEvents xTimer as new System.Windows.Forms.Timer

     Public Sub New(TickValue as integer)
         xTimer = new System.Windows.Forms.Timer
         xTimer.Interval = TickValue
     End Sub

     Public Sub StartTimer
         xTimer.Start
     End Sub

     Public Sub StopTimer
         xTimer.Stop
     End Sub

     Private Sub Timer_Tick Handles xTimer.Tick
         SampleProcedure
     End Sub

     Private Sub SampleProcedure
         'SomeCodesHERE
     End Sub

End Class

USAGE:

Dim xSub as new SampleCallEveryXMinute(60000) ' 1000 ms = 1 sec so 60000 ms = 1 min
xSub.StartTimer
like image 82
John Woo Avatar answered Sep 27 '22 23:09

John Woo


Yes, you could add a timer to the form, and set its interval to x*60000, where x is the number of minutes between calls.

Remember that the timer runs on the UI thread, so don't do anything intensive in the function. Also, if the UI thread is busy, the timer event will not fire until the UI thread finishes whatever event it is currently processing. If your function is going to be CPU-intensive, then consider having the timer start up a background worker

If you require a longer time period between function calls (ie, one thats too big for a timer interval) then you could have a timer function that fires every minute, and increments a counter until the desired amount of time has passed, before going on to call the function.

like image 30
William Lawn Stewart Avatar answered Sep 27 '22 23:09

William Lawn Stewart