How to use the same timer for different time intervals?

I use a timer in my code. Updating the status bar in a tick event by pressing the corresponding button for the time specified in the properties is indicated in one second. Now I want to use the same timer for a different time interval, say two seconds for another pronunciation. How to achieve this?

+4
source share
4 answers

I agree with @Henk and others.

But still, something like this might work:

Example

Int32 counter = 0; private void timer1_Tick(object sender, EventArgs e) { if (counter % 1 == 0) { OnOneSecond(); } if (counter % 2 == 0) { OnTwoSecond(); }) counter++; } 

Updated example

 private void Form_Load() { timer1.Interval = 1000; // 1 second timer1.Start(); // This will raise Tick event after 1 second OnTick(); // So, call Tick event explicitly when we start timer } Int32 counter = 0; private void timer1_Tick(object sender, EventArgs e) { OnTick(); } private void OnTick() { if (counter % 1 == 0) { OnOneSecond(); } if (counter % 2 == 0) { OnTwoSecond(); } counter++; } 
+2
source

Create a second timer. There is nothing to gain from breaking the first timer.

As @Henk noted, timers are not that expensive. (Especially not compared to committing, it's hard to maintain code!)

+5
source

Change the timer interval property.

0
source

Change the Interval property for each elapsed time. for example, software process data 30 seconds and sleep 10 seconds.

 static class Program { private System.Timers.Timer _sleepTimer; private bool _isSleeping = false; private int _processTime; private int _noProcessTime; static void Main() { _processTime = 30000; //30 seconds _noProcessTime = 10000; //10 seconds this._sleepTimer = new System.Timers.Timer(); this._sleepTimer.Interval = _processTime; this._sleepTimer.Elapsed += new System.Timers.ElapsedEventHandler(sleepTimer_Elapsed); ProcessTimer(); this._sleepTimer.Start(); } private void sleepTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { ProcessTimer(); } private void ProcessTimer() { _sleepTimer.Enabled = false; _isSleeping = !_isSleeping; if (_isSleeping) { _sleepTimer.Interval = _processTime; //process data HERE on new thread; } else { _sleepTimer.Interval = _noProcessTime; //wait fired thread and sleep Task.WaitAll(this.Tasks.ToArray()); } _sleepTimer.Enabled = true; } } 
0
source

Source: https://habr.com/ru/post/1332460/


All Articles