Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent of a timer tick of 30 minutes?

Tags:

c#

timer

I have a timer tick that I would like to kick off my backgroundworker every 30 minutes. What is the equivalent value of 30 minutes for a timer tick?

Below follows the code:

        _timer.Tick += new EventHandler(_timer_Tick);
        _timer.Interval = (1000) * (1);              
        _timer.Enabled = true;                       
        _timer.Start();       

    void _timer_Tick(object sender, EventArgs e)
    {
        _ticks++;
        if (_ticks == 15)
        {
            if (!backgroundWorker1.IsBusy)
            {
                backgroundWorker1.RunWorkerAsync();
            }

            _ticks = 0;
        }
    }

I am not sure if this is the best way or if anyone has a better suggestion.

like image 848
geoNeo_ Avatar asked Dec 02 '22 00:12

geoNeo_


2 Answers

The Interval property of a timer is specified in milliseconds, not ticks.

Therefore, for a timer which fires every 30 minutes, simply do:

// 1000 is the number of milliseconds in a second.
// 60 is the number of seconds in a minute
// 30 is the number of minutes.
_timer.Interval = 1000 * 60 * 30;

However, I'm not clear what the Tick event you use is. I think you mean Elapsed?

EDIT As CodeNaked makes clear, you are talking about the System.Windows.Forms.Timer, not the System.Timers.Timer. Luckily, my answer applies to both :)

Finally, I don't understand why you maintain a count (_ticks) within your timer_Tick method. You should re-write it as follows:

void _timer_Tick(object sender, EventArgs e)
{
    if (!backgroundWorker1.IsBusy)
    {
        backgroundWorker1.RunWorkerAsync();
    }
}
like image 110
RB. Avatar answered Dec 03 '22 13:12

RB.


To make the code more readable, you can use the TimeSpan class:

_timer.Interval = TimeSpan.FromMinutes(30).TotalMilliseconds;
like image 37
weston Avatar answered Dec 03 '22 13:12

weston