Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Disable and re-enable a dynamic System.Timers.Timer

Posted on 2016-11-21
6
Medium Priority
?
73 Views
Last Modified: 2016-11-23
Hello,

We have a windows service that creates several timers dynamically.

They execute every 20 seconds. sometimes this is enough time to do the processing, sometimes not.

So, we would like to be able to disable the timer, then re-enable it after processing has finished.

I tried creating a global list of timers and adding each timer to the list, then setting the properties, but this did not work.

All input is greatly appreciated.

resourcesys.
0
Comment
Question by:resourcesys
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
6 Comments
 
LVL 64

Expert Comment

by:Fernando Soto
ID: 41896140
Please post your code so we can see what you are working with so we can suggest some solutions.
0
 

Author Comment

by:resourcesys
ID: 41896186
Hello Fernando,

Firstly, using a repository object we get a list of classes (machine)

        Dim lstMachines As List(Of Machine) = objMachiness.GetMachines()

        For i As Integer = 0 To lstMachines.Count - 1
            Dim objTimer As New CustomTimer
            objTimer.MachineObject = lstMachines.Item(i)
            objTimer.Interval = 20000
            AddHandler objTimer.Elapsed, AddressOf Timer_Elapsed
            objTimer.Enabled = True
        Next

Open in new window


Then we have the method that carries out the processing:

    Private Sub Timer_Elapsed(ByVal sender As System.Object, ByVal e As System.Timers.ElapsedEventArgs)
        Dim objTimer As CustomerTimer = DirectCast(sender, CustomTimer)
        'Processing here
    End Sub

Open in new window


It's as simple as that.

I have tried disabling objTimer but that doesn't work it seems to disable all timers?

Thanks.

resourcesys
0
 
LVL 34

Expert Comment

by:it_saige
ID: 41896286
You probably want to implement a timer on each Machine object instead; e.g. -
Imports System.Timers

Module Module1
	Private machines As List(Of Machine)

	Sub Main()
		machines = (From i In Enumerable.Range(1, 20) Select New Machine() With {.ID = i, .Name = String.Format("Machine{0}", i), .CustomTimer = New Timer(i * 200)}).ToList()
		For Each [machine] As Machine In machines
			AddHandler [machine].TimerElapsed, AddressOf OnTimerElapsed
			Console.WriteLine("Starting the timer for {0}", [machine].Name)
			[machine].CustomTimer.Start()
		Next
		Console.ReadLine()
	End Sub

	Private Sub OnTimerElapsed(ByVal sender As Object, ByVal e As ElapsedEventArgs)
		If TypeOf sender Is Machine Then
			Dim m = DirectCast(sender, Machine)
			m.CustomTimer.Enabled = False
			Console.WriteLine("Stopping the timer for {0}", m.Name)
		End If
	End Sub
End Module

Class Machine
	Private ReadOnly fTimerElapsed As New List(Of ElapsedEventHandler)
	Public Custom Event TimerElapsed As ElapsedEventHandler
		AddHandler(value As ElapsedEventHandler)
			fTimerElapsed.Add(value)
		End AddHandler

		RemoveHandler(value As ElapsedEventHandler)
			fTimerElapsed.Remove(value)
		End RemoveHandler

		RaiseEvent(sender As Object, e As ElapsedEventArgs)
			For Each handler In fTimerElapsed
				Try
					handler.Invoke(sender, e)
				Catch ex As Exception
					Debug.WriteLine(String.Format("Exception while invoking event handler: {0}", ex))
				End Try
			Next
		End RaiseEvent
	End Event

	Private _customTimer As Timer

	Public Property ID() As Integer
	Public Property Name() As String

	Public Property CustomTimer() As Timer
		Get
			Return _customTimer
		End Get
		Set(ByVal value As Timer)
			_customTimer = value
			If _customTimer IsNot Nothing Then
				AddHandler _customTimer.Elapsed, AddressOf OnTimerElapsed
			End If
		End Set
	End Property

	Private Sub OnTimerElapsed(ByVal sender As Object, ByVal e As ElapsedEventArgs)
		RaiseEvent TimerElapsed(Me, e)
	End Sub
End Class

Open in new window

Which produces the following output -Capture.JPG
-saige-
0
RHCE - Red Hat OpenStack Prep Course

This course will provide in-depth training so that students who currently hold the EX200 & EX210 certifications can sit for the EX310 exam. Students will learn how to deploy & manage a full Red Hat environment with Ceph block storage, & integrate Ceph into other OpenStack service

 

Author Comment

by:resourcesys
ID: 41897273
Hello it_saige,

Thank you for your response.

This looks promising, so I will do some testing of my own and give you feedback on how it goes.

Thanks.

resourcesys
0
 
LVL 34

Accepted Solution

by:
it_saige earned 2000 total points
ID: 41897459
You will probably want to shore some of this up in order to make it more securable.  In all honesty, I would even question the validity of having the timer object as a publicly settable property.  I would see about using a constructor to pass the interval and move the logic for handler adding to that constructor; e.g. -
Imports System.Timers

Module Module1
	Private machines As List(Of Machine)

	Sub Main()
		machines = (From i In Enumerable.Range(1, 20) Select New Machine(i * 200) With {.ID = i, .Name = String.Format("Machine{0}", i)}).ToList()
		For Each [machine] As Machine In machines
			AddHandler [machine].TimerElapsed, AddressOf OnTimerElapsed
			Console.WriteLine("Starting the timer for {0}", [machine].Name)
			[machine].CustomTimer.Start()
		Next
		Console.ReadLine()
	End Sub

	Private Sub OnTimerElapsed(ByVal sender As Object, ByVal e As ElapsedEventArgs)
		If TypeOf sender Is Machine Then
			Dim m = DirectCast(sender, Machine)
			m.CustomTimer.Enabled = False
			Console.WriteLine("Stopping the timer for {0}", m.Name)
		End If
	End Sub
End Module

Class Machine
	Private ReadOnly fTimerElapsed As New List(Of ElapsedEventHandler)
	Public Custom Event TimerElapsed As ElapsedEventHandler
		AddHandler(value As ElapsedEventHandler)
			fTimerElapsed.Add(value)
		End AddHandler

		RemoveHandler(value As ElapsedEventHandler)
			fTimerElapsed.Remove(value)
		End RemoveHandler

		RaiseEvent(sender As Object, e As ElapsedEventArgs)
			For Each handler In fTimerElapsed
				Try
					handler.Invoke(sender, e)
				Catch ex As Exception
					Debug.WriteLine(String.Format("Exception while invoking event handler: {0}", ex))
				End Try
			Next
		End RaiseEvent
	End Event

	Private _customTimer As Timer
	Public Property ID() As Integer
	Public Property Name() As String
	Public Property CustomTimer() As Timer
		Get
			Return _customTimer
		End Get
		Private Set(value As Timer)
			If value IsNot Nothing AndAlso Not value.Equals(_customTimer) Then
				_customTimer = value
			End If
		End Set
	End Property

	Public Sub New(Optional interval As Double = 20)
		CustomTimer = New Timer(interval)
		AddHandler CustomTimer.Elapsed, AddressOf OnTimerElapsed
	End Sub

	Private Sub OnTimerElapsed(ByVal sender As Object, ByVal e As ElapsedEventArgs)
		RaiseEvent TimerElapsed(Me, e)
	End Sub
End Class

Open in new window


Which produces the same output as above.

-saige-
0
 

Author Closing Comment

by:resourcesys
ID: 41899423
Thanks it_saige, it worked great.

resourcesys.
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…
In response to a need for security and privacy, and to continue fostering an environment members can turn to for support, solutions, and education, Experts Exchange has created anonymous question capabilities. This new feature is available to our Pr…

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question