Timer problems
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 8 of 8

Thread: Timer problems

  1. #1
    Join Date
    Nov 2011
    Posts
    37

    Timer problems

    I have a timer that sends data to a text file every 5 minutes of the hour. The data, however, gets sent 1 second later every time. For example, it will send at 10:05:36 one time, then the next time it will send at 10:05:37. Is there a way I can fix it so it sends at the same increment?

  2. #2
    Join Date
    Aug 2008
    Posts
    902

    Re: Timer problems

    Post the relevant code so we can see what is really going on.

  3. #3
    Join Date
    Dec 2011
    Posts
    61

    Re: Timer problems

    try System.Timers.Timer instead of System.Windows.Forms.Timer

  4. #4
    Join Date
    Nov 2011
    Posts
    37

    Re: Timer problems

    I am using thread.sleep in my code. Is there better code to set up a timer?

  5. #5
    Join Date
    Aug 2008
    Posts
    902

    Re: Timer problems

    Sleep specifies a minimum amount of time to sleep for. It only checks that at least that much time has passed before resuming. It is perfectly alright for it to wait longer than you specify. Since you are not using a real-time OS, there is no way to guarantee an exact amount of time.

  6. #6
    Join Date
    Nov 2011
    Posts
    37

    Re: Timer problems

    Is there any solution to get a precise interval because my program will only send data if the time is divisible by 5 minutes?

  7. #7
    Join Date
    Aug 2008
    Posts
    902

    Re: Timer problems

    try something like this:

    Code:
    DateTime last = DateTime.Now;
    for (; ; )
    {
        while (DateTime.Now - last < TimeSpan.FromMinutes(5))
        {
            Thread.Sleep(100); //sleep a bit to not saturate the CPU
        }
        last = DateTime.Now;
        SendMyData(last.ToString());
    }

  8. #8
    Join Date
    Nov 2011
    Posts
    37

    Re: Timer problems

    I also have another issue with this program. I am trying to send data at a certain time, so I used a do while loop.

    do{
    //code
    }while(time.ToString("HHmm") != "1000")

    However, it does not run the rest of the code at 10:00. What should I do here?

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center