Search code examples
c#loopstimer

How to periodically trigger an time-lapse event every specific time interval


I wanted to create a time-lapse control, for example, when the program starts, after time interval t1, trigger event A (e.g switch on), then wait after time interval t2, trigger event B (e.g.switch off), and this process will be executed periodically for n times.

What I have achieved so far is I could loop the two events only when t1=t2, I don't know how to make t1 and t2 two separate controllable variables.

 public partial class Form1 : Form
    {

        private int counter; //counter to control the cycle times
        private int EventIndex;//control the event status

        private void InitializeTimer()
        {
            counter = 0;
            EventIndex = 0;
            timer1.Enabled = true; // Hook up timer's tick event handler.  
            this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
        }

        //function for switch the event status

        private void UpdateEvent()
        {
            EventIndex = 1 - EventIndex;  // loop event index between 1 and 0

            if (EventIndex.Equals(1))
            {
                //Exceute command for event A
            }
            else 
            {
                //Exceute command for event A
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            decimal t = numericUpDown1.Value; //time interval t between two events
            int interval = Convert.ToInt32(t);

            decimal n = numericUpDown2.Value; //periodically excute the process n times
            int cycle = Convert.ToInt32(n);

            //using the numeric input value to set up the interval time
            timer1.Interval = interval 


            if (counter >= cycle)  
            {
                // Exit loop code.  
                timer1.Enabled = false;
                counter = 0;

            }
            else
            {            
                UpdateEvent();
                counter = counter + 1;// Increment counter.
            }
        }
 }

Solution

  • Have UpdateEvent set the timer interval after an event:

    private void UpdateEvent()
    {
        if (EventIndex.Equals(1))
        {
            timer1.Interval = //delay until event B;
        }
        else 
        {
            timer1.Interval = //delay until event A;
        }
    }