简体   繁体   中英

How do I check how much time remains before timer fires next event?

For example, I have set timer1.Interval to 5000 and I would like to know how much of this interval remains before the timer ticks. How I can do it?

How to check timer time?

You cannot. The timer classes offer no way check how long remains before a timer is due to fire. The best you can do is to keep track of when the timer last fired and calculate yourself how long remains before the next tick.

        DateTime MainTimer_last_Tick = DateTime.Now;
        System.Windows.Forms.Timer timer_Calc_Remaining;
        timer_Calc_Remaining.Enabled = true;
        timer_Calc_Remaining.Interval = 100;
        timer_Calc_Remaining.Tick += new System.EventHandler(this.timer_Calc_Remaining_Tick);

on main timer start or tick:

   timer_Main.Enabled = true;
        MainTimer_last_Tick = DateTime.Now;


 private void timer_Calc_Remaining_Tick(object sender, EventArgs e)
        {
            int remaining_Milliseconds = (int)(MainTimer_last_Tick.AddMilliseconds(timer_Main.Interval).Subtract(DateTime.Now).TotalMilliseconds);
.../*
        int newValue = (timer_Main.Interval -remaining_Milliseconds) ;


        progressBar1.Maximum = timer_Main.Interval+1;

        progressBar1.Value = newValue ;*/



    }

You could use an alternative timer with an interval of 1000 (milliseconds). I don't think an interval of 1ms is really an option as this will stress the system too much and is unreliable anyway.

Every time this timer elapses, you can check the number of ticks (is this always a multitude of 1000?) and subtract it from (or use modulo) 5000.

But I can't:

That's because less than sign comes before equal sign and not the other way round

Its <= not =<

if (timer1.Interval <= 5000)
{
    //do something
}

You are using the Interval which is a property that will not be getting changed (It will always be 5000, so checking if it is smaller than 5000 is pointless). Also, if this code is in the Timer1_Tick function it will not be efficient. However, the code I believe you need is:

if (timer1.Interval <= 5000)
{
  //do something
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM