Reputation: 365
I am working on an application and I would like to create multiple timers that all fire at different intervals. On each fire I would like them to call a relevant function.
Initially, I would like a timer that fire every 100ms, 1 second, 10 second, 30second ect. On each "tick" I would like to call a function that reads data from a device and stores it in a buffer.
What is the best way to create the required timers and handle their events?
EDIT I have done something similar to this for each timer, but it's cumbersome, so looking for something simpler/smarter.
'Variables
Dim Timer100msUpdateInterval As DateInterval = 100
Dim Timer100msUpdate As Threading.Timer
'On Load
Dim TimerCallBack100ms As Threading.TimerCallback = New Threading.TimerCallback(AddressOf Timer100msUpdateTimerEvent)
Timer100msUpdate = New Threading.Timer(TimerCallBack100ms, Nothing, 100, Timer100msUpdateInterval)
'For each timer
Private Sub Timer100msUpdateTimerEvent(ByVal state As Object)
do100msTimerStuff()
End Sub
I like the concept approach by @kiLLua, but need some way to identify when each timer fires, which timer ran
Upvotes: 0
Views: 337
Reputation: 4506
Dim timers As New List(Of System.Threading.Timer)
timers.Add(New System.Threading.Timer(AddressOf MyHandler, Nothing, 100, 100))
timers.Add(New System.Threading.Timer(AddressOf MyHandler, Nothing, 1000, 1000))
timers.Add(New System.Threading.Timer(AddressOf MyHandler, Nothing, 10000, 10000))
timers.Add(New System.Threading.Timer(AddressOf MyHandler, Nothing, 30000, 30000))
where handler is defined as.
Sub MyHandler(state As Object)
End Sub
If your device cannot have 2 simultaneous requests then you'll need to implement some locking in MyHandler.
timers.Add(New System.Threading.Timer(AddressOf MyHandler, myDataRow, 30000, 30000))
Sub MyHandler(state As Object)
dim row = CType(state, DataRow)
...
End Sub
Upvotes: 1
Reputation: 471
Use Time interval
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
' Do What you want here
End Sub
Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
' Do What you want here
End Sub
' Have a private sub that handles each tick ..
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Timer1.Interval = 100 ' 100 ms
Timer2.Interval = 1000 ' 1 seconds
Timer3.Interval = 10000 ' 10 seconds
Timer4.Interval = 30000 ' 30 seconds
Timer1.Start() : Timer2.Start() : Timer3.Start() : Timer4.Start()
End Sub
There you go .. You can start from here..
Upvotes: 0