473,396 Members | 1,879 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Using System.Threading.Timer (SOS!)

I have just put together a vb.net app and now need to provide it to
users. This application needs to run the code in a sub every 60
seconds from a Windows Service application. I have the functionality
of the sub working fine but I cannot figure out how to run the timer.

The sub DoSomethingHere() needs to run every 60 seconds. It doesn't
need to change the interval or anything like that. It just needs to
run every 60 seconds as long as the service is running.

I have never used a timer and my attempts to make this work haven't
worked.

I'm hoping someone can show me how to do this in a Windows Service app
in vb.net.

Much Thanks!
lq

System.Threading.Timer code from MSDN:

'Start Code:
Imports Microsoft.VisualBasic
Imports System
Imports System.Threading

Public Class TimerExample

Shared Sub Main()

Dim autoEvent As New AutoResetEvent(False)
Dim statusChecker As New StatusChecker(10)

' Create the delegate that invokes methods for the timer.
Dim timerDelegate As TimerCallback = _
AddressOf statusChecker.CheckStatus

' Create a timer that signals the delegate to invoke
' CheckStatus after one second, and every 1/4 second
' thereafter.
Console.WriteLine("{0} Creating timer." & vbCrLf, _
DateTime.Now.ToString("h:mm:ss.fff"))
Dim stateTimer As Timer = _
New Timer(timerDelegate, autoEvent, 1000, 250)

' When autoEvent signals, change the period to every
' 1/2 second.
autoEvent.WaitOne(5000, False)
stateTimer.Change(0, 500)
Console.WriteLine(vbCrLf & "Changing period." & vbCrLf)

' When autoEvent signals the second time, dispose of
' the timer.
autoEvent.WaitOne(5000, False)
stateTimer.Dispose()
Console.WriteLine(vbCrLf & "Destroying timer.")

End Sub
End Class

Public Class StatusChecker

Dim invokeCount, maxCount As Integer

Sub New(count As Integer)
invokeCount = 0
maxCount = count
End Sub

' This method is called by the timer delegate.
Sub CheckStatus(stateInfo As Object)
Dim autoEvent As AutoResetEvent = _
DirectCast(stateInfo, AutoResetEvent)
invokeCount += 1
Console.WriteLine("{0} Checking status {1,2}.", _
DateTime.Now.ToString("h:mm:ss.fff"), _
invokeCount.ToString())

If invokeCount = maxCount Then

' Reset the counter and signal to stop the timer.
invokeCount = 0
autoEvent.Set()
End If
End Sub

End Class

Mar 23 '07 #1
4 14368
On Mar 23, 1:30 pm, "Lauren Quantrell" <laurenquantr...@hotmail.com>
wrote:
I have just put together a vb.net app and now need to provide it to
users. This application needs to run the code in a sub every 60
seconds from a Windows Service application. I have the functionality
of the sub working fine but I cannot figure out how to run the timer.

The sub DoSomethingHere() needs to run every 60 seconds. It doesn't
need to change the interval or anything like that. It just needs to
run every 60 seconds as long as the service is running.

I have never used a timer and my attempts to make this work haven't
worked.

I'm hoping someone can show me how to do this in a Windows Service app
in vb.net.

Much Thanks!
lq

System.Threading.Timer code from MSDN:

'Start Code:

Imports Microsoft.VisualBasic
Imports System
Imports System.Threading

Public Class TimerExample

Shared Sub Main()

Dim autoEvent As New AutoResetEvent(False)
Dim statusChecker As New StatusChecker(10)

' Create the delegate that invokes methods for the timer.
Dim timerDelegate As TimerCallback = _
AddressOf statusChecker.CheckStatus

' Create a timer that signals the delegate to invoke
' CheckStatus after one second, and every 1/4 second
' thereafter.
Console.WriteLine("{0} Creating timer." & vbCrLf, _
DateTime.Now.ToString("h:mm:ss.fff"))
Dim stateTimer As Timer = _
New Timer(timerDelegate, autoEvent, 1000, 250)

' When autoEvent signals, change the period to every
' 1/2 second.
autoEvent.WaitOne(5000, False)
stateTimer.Change(0, 500)
Console.WriteLine(vbCrLf & "Changing period." & vbCrLf)

' When autoEvent signals the second time, dispose of
' the timer.
autoEvent.WaitOne(5000, False)
stateTimer.Dispose()
Console.WriteLine(vbCrLf & "Destroying timer.")

End Sub
End Class

Public Class StatusChecker

Dim invokeCount, maxCount As Integer

Sub New(count As Integer)
invokeCount = 0
maxCount = count
End Sub

' This method is called by the timer delegate.
Sub CheckStatus(stateInfo As Object)
Dim autoEvent As AutoResetEvent = _
DirectCast(stateInfo, AutoResetEvent)
invokeCount += 1
Console.WriteLine("{0} Checking status {1,2}.", _
DateTime.Now.ToString("h:mm:ss.fff"), _
invokeCount.ToString())

If invokeCount = maxCount Then

' Reset the counter and signal to stop the timer.
invokeCount = 0
autoEvent.Set()
End If
End Sub

End Class
This page:

http://msdn2.microsoft.com/en-us/lib...8a(VS.80).aspx

and then this page:

http://msdn2.microsoft.com/en-us/lib...er(VS.80).aspx

is what I used to figure this out once.

Sorry, don't have the code available to post.

Mar 23 '07 #2
Lauren Quantrell wrote:
I have just put together a vb.net app and now need to provide it to
users. This application needs to run the code in a sub every 60
seconds from a Windows Service application. I have the functionality
of the sub working fine but I cannot figure out how to run the timer.

The sub DoSomethingHere() needs to run every 60 seconds. It doesn't
need to change the interval or anything like that. It just needs to
run every 60 seconds as long as the service is running.
<snip>

I didn't understand exactly what the thread must do: perform some action
then wait 60 seconds and repeat, or perform an action at each 60 seconds,
which would mean to spawn another thread if the previous one hadn't finished
yet (in case the thread activity lasts more than 60 seconds).

In the first case, the thread itself can control its inactivity (you don't
really need a timer). In the second case, it would be the job of a
controller thread to spawn new threads at each 60 secs... Also in this case
the controller thread itself could take care of the intervals between the
activity, you wouldn't need a timer also (or so it seems to me).

A simplistic approach would be for the worker (or controller) thread to just
call Sleep with the desired interval. The problem is that your service may
need to finish while the other thread is still sleeping, which would mean to
wait for the complete interval to ellapse and the thread to awake. Not a
good thing, if you ask me. Another possibility would be for the secondary
thread to wait on a controlled resource (say, a ManualResetEvent) with a
timeout for the current interval. Hack, I guess this is better shown than
explained...

<aircode>
'Use an event to get the appropriate interval
Public Class IntervalEventArgs
Inherits EventArgs
Public Property Interval() As Integer
End Property
End Class

'...
'In the class that controls the thread activity
'(your main class, probably)
Private WithEvents mWorker As Worker
Private mEvent As New ManualResetEvent(False)
Private mThread As Thread

Private Sub Worker_Interval( _
ByVal Sender As Object, _
ByVal E As IntervalEventArgs _
) Handles mWorker.Interval

E.Interval = 'Assign an appropriate interval

End Sub

Public Sub StartWorking()
'Creates the thread that will execute the work
If mWorker Is Nothing Then
mEvent.Reset()
mWorker = New Worker(mEvent)
mThread = New Thread(AddressOf mWorker.DoWork)
mThread.Start()
End If

End Sub

Public Sub StopWorking()
'Cancels the worker thread
If mWorker IsNot Nothing Then
Dim Temp As Worker = mWorker
mWorker = Nothing
Temp.Cancel = True

'If the worker is sleeping,
'this will bring it back
'from dream-land
mEvent.Set()

'waits for the thread to finish (hopefully)
'-- a timeout may be advised...
mThread.Join()

End If
End Sub

'...
'The worker class
Public Class Worker

Public Event Interval( _
ByVal Sender As Object, _
ByVal E As IntervalEventArgs)

Private mEvent As ManualResetEvent

Public Sub New(ByVal SourceEvent As ManualResetEvent)
mEvent = SourceEvent
End Sub

Public Property Cancel() As Boolean
'Allows a caller to cancel the thread operation
'in the middle of work -- must be checked by
'the thread periodically
End Property

Sub DoWork()
Dim Args As New IntervalEventArgs
Do
'starts getting the current interval from the
'main app
RaiseEvent Interval(Me, Args)

'waits or times-out (the expected behavior)
mEvent.WaitOne(Args.Interval, False)

If Cancel Then Exit Do

'... Do work
'... Don't forget to check Cancel
'... periodically!
Loop
End Sub
End Class
</aircode>

HTH.

Regards,

Branco.
(Rats, Google Groups seems to be down...)
Mar 23 '07 #3
On Mar 23, 5:34 pm, "Branco Medeiros" <branco.medei...@gmail.com>
wrote:
Lauren Quantrell wrote:
I have just put together a vb.net app and now need to provide it to
users. This application needs to run the code in a sub every 60
seconds from a Windows Service application. I have the functionality
of the sub working fine but I cannot figure out how to run the timer.
The sub DoSomethingHere() needs to run every 60 seconds. It doesn't
need to change the interval or anything like that. It just needs to
run every 60 seconds as long as the service is running.

<snip>

I didn't understand exactly what the thread must do: perform some action
then wait 60 seconds and repeat, or perform an action at each 60 seconds,
which would mean to spawn another thread if the previous one hadn't finished
yet (in case the thread activity lasts more than 60 seconds).

In the first case, the thread itself can control its inactivity (you don't
really need a timer). In the second case, it would be the job of a
controller thread to spawn new threads at each 60 secs... Also in this case
the controller thread itself could take care of the intervals between the
activity, you wouldn't need a timer also (or so it seems to me).

A simplistic approach would be for the worker (or controller) thread to just
call Sleep with the desired interval. The problem is that your service may
need to finish while the other thread is still sleeping, which would mean to
wait for the complete interval to ellapse and the thread to awake. Not a
good thing, if you ask me. Another possibility would be for the secondary
thread to wait on a controlled resource (say, a ManualResetEvent) with a
timeout for the current interval. Hack, I guess this is better shown than
explained...

<aircode>
'Use an event to get the appropriate interval
Public Class IntervalEventArgs
Inherits EventArgs
Public Property Interval() As Integer
End Property
End Class

'...
'In the class that controls the thread activity
'(your main class, probably)
Private WithEvents mWorker As Worker
Private mEvent As New ManualResetEvent(False)
Private mThread As Thread

Private Sub Worker_Interval( _
ByVal Sender As Object, _
ByVal E As IntervalEventArgs _
) Handles mWorker.Interval

E.Interval = 'Assign an appropriate interval

End Sub

Public Sub StartWorking()
'Creates the thread that will execute the work
If mWorker Is Nothing Then
mEvent.Reset()
mWorker = New Worker(mEvent)
mThread = New Thread(AddressOf mWorker.DoWork)
mThread.Start()
End If

End Sub

Public Sub StopWorking()
'Cancels the worker thread
If mWorker IsNot Nothing Then
Dim Temp As Worker = mWorker
mWorker = Nothing
Temp.Cancel = True

'If the worker is sleeping,
'this will bring it back
'from dream-land
mEvent.Set()

'waits for the thread to finish (hopefully)
'-- a timeout may be advised...
mThread.Join()

End If
End Sub

'...
'The worker class
Public Class Worker

Public Event Interval( _
ByVal Sender As Object, _
ByVal E As IntervalEventArgs)

Private mEvent As ManualResetEvent

Public Sub New(ByVal SourceEvent As ManualResetEvent)
mEvent = SourceEvent
End Sub

Public Property Cancel() As Boolean
'Allows a caller to cancel the thread operation
'in the middle of work -- must be checked by
'the thread periodically
End Property

Sub DoWork()
Dim Args As New IntervalEventArgs
Do
'starts getting the current interval from the
'main app
RaiseEvent Interval(Me, Args)

'waits or times-out (the expected behavior)
mEvent.WaitOne(Args.Interval, False)

If Cancel Then Exit Do

'... Do work
'... Don't forget to check Cancel
'... periodically!
Loop
End Sub
End Class
</aircode>

HTH.

Regards,

Branco.
(Rats, Google Groups seems to be down...)

Branco,
Thanks for the thorough explanation. I'll check this out.

Mar 24 '07 #4
On Mar 23, 3:25 pm, z...@construction-imaging.com wrote:
On Mar 23, 1:30 pm, "Lauren Quantrell" <laurenquantr...@hotmail.com>
wrote:


I have just put together a vb.net app and now need to provide it to
users. This application needs to run the code in a sub every 60
seconds from a Windows Service application. I have the functionality
of the sub working fine but I cannot figure out how to run the timer.
The sub DoSomethingHere() needs to run every 60 seconds. It doesn't
need to change the interval or anything like that. It just needs to
run every 60 seconds as long as the service is running.
I have never used a timer and my attempts to make this work haven't
worked.
I'm hoping someone can show me how to do this in a Windows Service app
in vb.net.
Much Thanks!
lq
System.Threading.Timer code from MSDN:
'Start Code:
Imports Microsoft.VisualBasic
Imports System
Imports System.Threading
Public Class TimerExample
Shared Sub Main()
Dim autoEvent As New AutoResetEvent(False)
Dim statusChecker As New StatusChecker(10)
' Create the delegate that invokes methods for the timer.
Dim timerDelegate As TimerCallback = _
AddressOf statusChecker.CheckStatus
' Create a timer that signals the delegate to invoke
' CheckStatus after one second, and every 1/4 second
' thereafter.
Console.WriteLine("{0} Creating timer." & vbCrLf, _
DateTime.Now.ToString("h:mm:ss.fff"))
Dim stateTimer As Timer = _
New Timer(timerDelegate, autoEvent, 1000, 250)
' When autoEvent signals, change the period to every
' 1/2 second.
autoEvent.WaitOne(5000, False)
stateTimer.Change(0, 500)
Console.WriteLine(vbCrLf & "Changing period." & vbCrLf)
' When autoEvent signals the second time, dispose of
' the timer.
autoEvent.WaitOne(5000, False)
stateTimer.Dispose()
Console.WriteLine(vbCrLf & "Destroying timer.")
End Sub
End Class
Public Class StatusChecker
Dim invokeCount, maxCount As Integer
Sub New(count As Integer)
invokeCount = 0
maxCount = count
End Sub
' This method is called by the timer delegate.
Sub CheckStatus(stateInfo As Object)
Dim autoEvent As AutoResetEvent = _
DirectCast(stateInfo, AutoResetEvent)
invokeCount += 1
Console.WriteLine("{0} Checking status {1,2}.", _
DateTime.Now.ToString("h:mm:ss.fff"), _
invokeCount.ToString())
If invokeCount = maxCount Then
' Reset the counter and signal to stop the timer.
invokeCount = 0
autoEvent.Set()
End If
End Sub
End Class

This page:

http://msdn2.microsoft.com/en-us/lib...8a(VS.80).aspx

and then this page:

http://msdn2.microsoft.com/en-us/lib...er(VS.80).aspx

is what I used to figure this out once.

Sorry, don't have the code available to post.- Hide quoted text -

- Show quoted text -
Thanks! I scoured MSDN and for the code above but didn't come across
these.

Mar 24 '07 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: ELO | last post by:
Hi all Every week, I need to get two files on a remote server. I have developped a C# Windows Service with two System.Threading.Timer to do this task For the first one, the delay (TimeSpan...
4
by: Hagay Lupesko | last post by:
Hi, I've encountered a strange phenomena which appears to me as a bug: I have an engine that uses a System.Threading.Timer to invoke a delegate every X minutes. The code looks something...
3
by: Andy | last post by:
Hello. I want to use System.Threading.Timer to control when my windows form is invalidated. I want it to update at 60 frames per second. But, if I set the Interval of my timer to anything less than...
6
by: Dan | last post by:
I've created a pocketpc app which has a startup form containing a listview. The form creates an object which in turn creates a System.Threading.Timer. It keeps track of the Timer state using a...
2
by: linesh.gajera | last post by:
Hi Guys, I am creating a Windows service that call a routine at given interval. Once routine is complete, windows service should wait for 5 minutes and then call the routine again. I was using...
2
by: steve | last post by:
Since System.Threading.Timer uses the threadpool to do its stuff what happens when (a) You try to create a timer and the thread pool is *exhausted* (b) The timer is due to fire AND all threads...
0
by: Kelsang Wangchuk | last post by:
Hi Just a quick question... When would you use System.Timers.Timer, and when System.Threading.Timer? What are the principal differences between them? There is a lot of discussion about...
2
by: Stig Hausberg | last post by:
Hi folks! I'm currently working in a prototype project as we are moving into dotnet and I've have stumbled upon an issue someone hopefully can help me with. The system we are building needs to...
0
by: Bruce | last post by:
Hi I have a question on using System.Threading.Timer. I understand that in order for the timer to work, I need to store a reference to the timer so that it does not get garbage collected. In my...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.