0

I am programming some program that will generate statistics. For the recording of statistics I currently use a timer (set to 1000ms).

But it's not accurate. I have seen that after a while it is lower than the actual time. I think this has to do something with the CPU and stuff.

So my question: What is a good way to call a function every second?

By the way, this is what a part of my code looks like:

int totalSeconds = 0; // this number was taken from a savefile
int sessionSeconds = 0; // this number is for the session time

bool doUpdateGUI = true; // this is true when the form is shown

private void TimerMAIN_Tick()
{
    totalSeconds++; // increase by 1
    sessionSeconds++; // increase by 1

    if (doUpdateGUI == true)
    {
    updateGUI(); // call the updateGUI void (which updates labels and textboxes)
    }
}

Edit: I got the answer myself! I created it like this:

private void timerTClockEngine_Tick(object sender, EventArgs e) //this timer is set to 100ms
        {
            dt = DateTime.Now;
            if (dt.Second != oldSec)
            {
                TClock_TICK();
                oldSec = dt.Second;
            }
        }

        private void TClock_TICK()
        {
            Ttime++;
            textBoxT.Text = Ttime.ToString();
        }
Mr. Coder
  • 1
  • 3
  • Are you running the timer in a separate thread? – SteveFerg Aug 15 '15 at 19:59
  • 1
    What do you mean with "once every second"? If the function takes 0.1 sec to execute, should the next execution be 1 sec after the END of the previous call or the BEGINNING of the next call? – xanatos Aug 15 '15 at 19:59
  • 4
    *every exact second* - ***impossible***. Not even universally defined. – Amit Aug 15 '15 at 20:03
  • @xanatos I mean calling a function every time the computer time second goes up. Without the function time. (the function doesn't do much btw, just increases a couple of ints by 1) – Mr. Coder Aug 15 '15 at 20:06
  • It is always complex, because nearly all the timers of .NET are low precision, and are "best effort"... There is something [here](http://stackoverflow.com/a/31612770/613130) (plus the [original response](https://social.msdn.microsoft.com/Forums/en-US/6cd5d9e3-e01a-49c4-9976-6c6a2f16ad57/1-millisecond-timer)) – xanatos Aug 15 '15 at 20:17
  • why you want it in exact seconds. i mean if you are using [this way](http://stackoverflow.com/a/6169305/4767498) how a few milliseconds can be the problem – M.kazem Akhgary Aug 15 '15 at 20:42
  • @Amit its possible to be much more accurate than this(not exact) but i think hardware are not designed for this purpose! – M.kazem Akhgary Aug 15 '15 at 20:44
  • 1
    @M.kazemAkhgary - sure, but if the task either: 1. makes no sense because it's impossible. Or 2. not really important to be accurate then the question is pointless. Maybe my comment should have been a bit more suggestive in terms of making Mr. Coder think about the his question... – Amit Aug 15 '15 at 20:49

0 Answers0