Solved

Timer usage and efficiencies Visual Basic 2008

Posted on 2009-07-09
17
186 Views
Last Modified: 2013-11-26
If I have a timer that executes a event of posting a message for 15 minutes at a specific time of day (Say 12 to 12:15), would it be better to have the interval of the timer set to 15 minutes and 1 second (901000) so that it isn't running at intervals of 1000 (Firing every second)?

Just looking for efficiencies within the process of the code. Not sure this makes any difference in memory usage or so small it is insignificant. (Understanding that many insignificants added up make it significant)

Thanks in advance.
0
Comment
Question by:technicaltrader
[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
  • 10
  • 7
17 Comments
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 24815200
If you have it set at 15 minutes and 1 second then it may fire just BEFORE your time window and then you won't get another event until just AFTER your desired window.  This would result in your Label NOT being updated at all during your target period!

If you are going to POLL the time (which is what you're doing) then you have to make a tradeoff between how quickly you determine that you are in the window and how often you want to check the time.  

Maybe 15 or 30 seconds would be better?

If you like I can show you how to write a class that SLEEPS until the window is hit and then raises a custom EVENT to notify you...
0
 

Author Comment

by:technicaltrader
ID: 24815363
Yeah. I wondered if a 15 to 30 second buffer would be better for the reasons you stated.

Yes, If you could give me an example of a class the SLEEPS, that would be great!

Thanks for your rationale of this. Really helps my understanding out.
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 24815572
From your previous question, we were only "in the window" on Mon-Fri.  Is this still the case?
0
Containers and Docker for Everyone

Containers are an incredibly powerful technology that can provide you and/or your engineering team with huge productivity gains. Using containers, you can deploy, back up, replicate, and move apps and their dependencies quickly and easily.

 

Author Comment

by:technicaltrader
ID: 24815900
Yes. That will always be the case. Mon - Fri.

There is a variable I was going to address at a later date after I got used to these ways is that how to display the message at specific times related to time zones.

So If I had a message to display at 12:00pm Central time on one computer, but would need to display at 1:00pm eastern time on another depending on where I am using this project. Reason being is that the messaging that will be going on has to do with specific eastern time events that translates to time zones elsewhere. The events will always be based on eastern time. (Hope that makes sense)

If this subject is premature then that is fine. Thought I would throw that in there just in case it may simplify things.

Thank you!...
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 24816330
So is everyone supposed to get the lunch message only when it is between 12:00 and 12:15, Monday thru Friday, in EASTERN TIME?
(probably not)

...but I think you're thinking ahead with a different problem?

It is possible to convert between time zones.  In the example below, I display what 1:00 pm on Friday, July 9th, 2009 in the Eastern Time Zone would be in the Local Time Zone:

        Dim EasternZone As TimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")
        Dim Friday1300 As New DateTime(2009, 7, 9, 13, 0, 0, 0) ' Friday at 1:00 pm
        Dim LocalApptTime As DateTime = TimeZoneInfo.ConvertTime(Friday1300, EasternZone, TimeZoneInfo.Local)
        MessageBox.Show(LocalApptTime.ToString, "Local Appt Time")

I'll post the example for the original question too...
0
 

Author Comment

by:technicaltrader
ID: 24816505
Well, the application is used with the New York Stock Exchange that is on Eastern time.

I use the message "Lunch Time" as I want it posted when Eastern lunch time basically is as a reminder. So that would translate to 11 central 10 mountain and 9 pacific depending on what time zone our computer clocks are set to.

(There is certain actions that happen around Eastern time at 12:00 in the markets is the reasons behind this just for one example. There are actually 7 timed events that eventually I will set up to post a messaging reminder)
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 24816538
Ok...so we can use code like I posted above to figure out what the local equivalent time is (regardless of where we are) to the Eastern Time Zone.

I'll code up the full blown example.
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 24818814
I was driving all night (taking wife and her girl scout troop to LAX) and just can't think right now.

I'll post an example tomorrow...sorry!   =)
0
 

Author Comment

by:technicaltrader
ID: 24819052
Oh my. No problem! Take care!

0
 
LVL 86

Accepted Solution

by:
Mike Tomlinson earned 500 total points
ID: 24828486
Alrighty...try this out on a form with a Label.

You can create multiple instances of the Notification Class and specify a different name, time, and duration for each:

    Dim notif As New Notification("Lunch", New TimeSpan(13, 0, 0), 15)

The "Lunch" notification in the example will fire at 1:00 pm and last 15 minutes.  Use 24 hour format to specify the time (1 would be 1:00 am).  The times are Absolute Eastern times and will be converted automatically to whatever time zone the users computer is set to.  They will only fire on weekdays (mon --> fri).

Here's the code:
Public Class Form1
 
    Private notifs As New List(Of Notification)
 
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim notif As New Notification("Lunch", New TimeSpan(13, 0, 0), 15)
        AddHandler notif.EventStart, AddressOf notif_EventStart
        AddHandler notif.EventStop, AddressOf notif_EventStop
        notifs.Add(notif)
        notif.Start()
    End Sub
 
    Private Sub notif_EventStart(ByVal sender As Notification)
        Label1.Text = sender.Name & " started"
    End Sub
 
    Private Sub notif_EventStop(ByVal sender As Notification)
        Label1.Text = sender.Name & " stopped"
    End Sub
 
    Private Class Notification
 
        Private _Name As String
        Private _Time As TimeSpan
        Private _Duration As Integer
        Private EasternZone As TimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")
 
        Private SC As System.Threading.SynchronizationContext
        Public Event EventStart(ByVal sender As Notification)
        Public Event EventStop(ByVal sender As Notification)
 
        Public ReadOnly Property Name() As String
            Get
                Return _Name
            End Get
        End Property
 
        Public Sub New(ByVal Name As String, ByVal Time As TimeSpan, ByVal Duration As Integer)
            _Name = Name
            _Time = Time
            _Duration = Duration
            SC = System.Windows.Forms.WindowsFormsSynchronizationContext.Current
        End Sub
 
        Public Sub Start()
            Dim T As New System.Threading.Thread(AddressOf Sleeper)
            T.IsBackground = True
            T.Start()
        End Sub
 
        Private Sub Sleeper()
            Dim LocalStartDT, LocalStopDT As DateTime
 
            ' find the first event window that isn't in the past
            Dim refDT As New DateTime(Date.Today.Year, Date.Today.Month, Date.Today.Day, 0, 0, 0, DateTimeKind.Unspecified)
            Dim FoundOne As Boolean
            Do
                FoundOne = True
                GetNextEventLocal(refDT, LocalStartDT, LocalStopDT)
                If DateTime.Now.Subtract(LocalStopDT).TotalMilliseconds >= 0 Then
                    FoundOne = False
                    refDT = refDT.AddDays(1)
                End If
            Loop While Not FoundOne
 
            ' see if we are "in" the current window.
            ' if so, we need to finish the partial cycle before the main loop below
            If DateTime.Now.Subtract(LocalStartDT).TotalMilliseconds >= 0 Then
                ' update the status (we are PAST the beginning of this window)
                SC.Post(New System.Threading.SendOrPostCallback(AddressOf RaiseStart), Nothing)
 
                ' wait for the end of the window
                System.Threading.Thread.Sleep(LocalStopDT.Subtract(DateTime.Now).TotalMilliseconds)
                SC.Post(New System.Threading.SendOrPostCallback(AddressOf RaiseStop), Nothing)
 
                ' get the next window
                refDT = refDT.AddDays(1)
                GetNextEventLocal(refDT, LocalStartDT, LocalStopDT)
            Else
                ' update the status (we have NOT reached the window yet)
                SC.Post(New System.Threading.SendOrPostCallback(AddressOf RaiseStop), Nothing)
            End If
 
            While True
                Debug.Print("Next Event Notification:")
                Debug.Print("Start: " & LocalStartDT)
                Debug.Print(" Stop: " & LocalStopDT)
 
                ' sleep until the beginning of the event
                System.Threading.Thread.Sleep(LocalStartDT.Subtract(DateTime.Now).TotalMilliseconds)
                SC.Post(New System.Threading.SendOrPostCallback(AddressOf RaiseStart), Nothing)
 
                ' sleep until the end of the event
                System.Threading.Thread.Sleep(LocalStopDT.Subtract(DateTime.Now).TotalMilliseconds)
                SC.Post(New System.Threading.SendOrPostCallback(AddressOf RaiseStop), Nothing)
 
                ' get the next event window
                refDT = refDT.AddDays(1)
                GetNextEventLocal(refDT, LocalStartDT, LocalStopDT)
            End While
        End Sub
 
        Private Sub GetNextEventLocal(ByVal RefDT As DateTime, ByRef StartDT As DateTime, ByRef StopDT As DateTime)
            Dim EastStartDT As DateTime = RefDT.Add(_Time)
            While EastStartDT.DayOfWeek = DayOfWeek.Saturday Or EastStartDT.DayOfWeek = DayOfWeek.Sunday
                EastStartDT = EastStartDT.AddDays(1)
            End While
            Dim EastStopDT As DateTime = EastStartDT.AddMinutes(_Duration)
 
            StartDT = TimeZoneInfo.ConvertTime(EastStartDT, EasternZone, TimeZoneInfo.Local)
            StopDT = TimeZoneInfo.ConvertTime(EastStopDT, EasternZone, TimeZoneInfo.Local)
        End Sub
 
        Private Sub RaiseStart()
            RaiseEvent EventStart(Me)
        End Sub
 
        Private Sub RaiseStop()
            RaiseEvent EventStop(Me)
        End Sub
 
    End Class
 
End Class

Open in new window

0
 

Author Closing Comment

by:technicaltrader
ID: 31602445
Thank you!!! Wow, this is above and beyond what I expected. I am working with this code right now. Get it set up. I will follow up with you and let you know how this is doing, but for now will close this out and give the points. Thank you, Thank you Thank you!... Appreciation to follow!...
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 24831225
Glad that was helpful.  I hope you can successfully integrate that into your app and use it for your other types of event notifications...

Feel free to ask questions...I added some comments in there but the approach I utilized isn't seen often in examples so I understand if it's hard to "digest".  ;)
0
 

Author Comment

by:technicaltrader
ID: 24853649
This is working out real well. Producing many events that I need to do throughout the day.

Another question is, how will this code work with daylight savings time and say places like China that don't use DST and also when we go off of DST? Does this code adjust?

Just curious...

0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 24853977
I think it does since we are getting times in the Eastern Time Zone:

    Private EasternZone As TimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")

And tHen converting them to the Local Time Zone:

    StartDT = TimeZoneInfo.ConvertTime(EastStartDT, EasternZone, TimeZoneInfo.Local)

See: http://msdn.microsoft.com/en-us/library/bb397783.aspx

If the Time Zone exists then it should have the correct rules assigned to it.  I haven't really tested it out though!  =\
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 24853996
The example here involving Hawaiian time implies that it correctly adjust for DST too:
http://msdn.microsoft.com/en-us/library/bb397769.aspx 
0
 

Author Comment

by:technicaltrader
ID: 24854194
Hey Thanks again! I couldn't wrap my head around that question of DST. Some of the messaging I MAY be using would reference trading hours on the Hang Seng in China which they don't use DST as well as Japan too.

Thanks for your reply!
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 24854202
You should be able to get the "China" Time Zone (or whatever they use) and then convert it to local...and the local will know if it needs to take into account DST.
0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

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

For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
This video Micro Tutorial shows how to password-protect PDF files with free software. Many software products can do this, such as Adobe Acrobat (but not Adobe Reader), Nuance PaperPort, and Nuance Power PDF, but they are not free products. This vide…

726 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