none
How to stop previous interval and start new interval timer in C# RRS feed

  • Question

  • How to stop previous interval(elapsedEvent) and start new interval(elapsedEvent) timer in C#.

    Ex: I had interval with one hour with interval(elapsedEvent) , later user changed to two hours with interval(elapsedEvent).

    While I tried to change one hour to two hour interval (elapsedEvent), it is coming for both one and two hours  as well.

    Need to chnage the interval (elapsedEvent) of timer what I given.


    R L Kiran


    Tuesday, July 10, 2018 3:57 PM

All replies

  • You didn't clarify what type of timer you're using. There are 2 in the core framework and 1 for each UI.

    Since you mentioned elapsedEvent I'm going to assume you're referring to ElapsedEventArgs which is from System.Timers.Timer. In that case cast the sender to Timer and then just change the Interval property. You might want to call Stop first and then call Start to have it begin again.

    void timer_Elapsed ( object sender, ElapsedEventArgs e )
    {
       var timer = sender as Timer;
    
       timer.Stop();
       timer.Interval = new TimeSpan(2, 0, 0);
       timer.Start();
    }


    Michael Taylor http://www.michaeltaylorp3.net

    Tuesday, July 10, 2018 9:49 PM
    Moderator
  • Hi Kiran Reddi,

    Thank you for posting here.

    For your question, you could use the Timer.Change Method to change the start time and the interval between method invocations for a timer.

    class Timer_example
        {
            public static void Main()
            {
                 AutoResetEvent autoEvent = new AutoResetEvent(false);
                StatusChecker statusChecker = new StatusChecker(10);
    
                // Create the delegate that invokes methods for the timer.
                TimerCallback timerDelegate =
                    new TimerCallback(statusChecker.CheckStatus);
    
                TimeSpan delayTime = new TimeSpan(0, 0, 1);
                TimeSpan intervalTime = new TimeSpan(0, 0, 0, 0, 250);
    
                // Create a timer that signals the delegate to invoke 
                // CheckStatus after one second, and every 1/4 second 
                // thereafter.
                Console.WriteLine("{0} Creating timer.\n",
                    DateTime.Now.ToString("h:mm:ss.fff"));
                System.Threading.Timer stateTimer = new System.Threading.Timer(
                    timerDelegate, autoEvent, delayTime, intervalTime);
    
                // When autoEvent signals, change the period to every 
                // 1/2 second.
                autoEvent.WaitOne(5000, false);
                stateTimer.Change(new TimeSpan(0),
                    intervalTime + intervalTime);
                Console.WriteLine("\nChanging period.\n");
    
                // When autoEvent signals the second time, dispose of 
                // the timer.
                autoEvent.WaitOne(5000, false);
                stateTimer.Dispose();
                Console.WriteLine("\nDestroying timer.");
            }
        }
    
        class StatusChecker
        {
            int invokeCount, maxCount;
    
            public StatusChecker(int count)
            {
                invokeCount = 0;
                maxCount = count;
            }
    
            // This method is called by the timer delegate.
            public void CheckStatus(Object stateInfo)
            {
                AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
                Console.WriteLine("{0} Checking status {1,2}.",
                    DateTime.Now.ToString("h:mm:ss.fff"),
                    (++invokeCount).ToString());
    
                if (invokeCount == maxCount)
                {
                    // Reset the counter and signal Main.
                    invokeCount = 0;
                    autoEvent.Set();
                }
            }
        }
    

    I use a gif to show the results.

    For more details, please refer to the MSDN documents.

    https://msdn.microsoft.com/en-us/library/317hx6fa(v=vs.110).aspx

    Best Regards,

    Wendy


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, July 11, 2018 9:57 AM
    Moderator
  • Hi Michael, Thanks for quick reply,

    Here I try to use Timer in asp.net C# application.

    how to stop timer previous interval and go for next given interval in asp.net web application


    R L Kiran

    Wednesday, July 11, 2018 3:43 PM
  • The code I posted should be fine for your timer. Did you try it?

    Note that asp.net is request based so you cannot just create a timer and expect it to work. At a minimum the timer would need to be static or globally available otherwise it wouldn't survive the request. You should post in the asp.net forums for help with that. 


    Michael Taylor http://www.michaeltaylorp3.net

    Wednesday, July 11, 2018 4:04 PM
    Moderator
  • OKay Thanks Michael

    R L Kiran

    Wednesday, July 11, 2018 4:06 PM
  • Hi Wendy Zang,

      Thanks for explanation , I am looking into Timer in asp.net web application 

    as code below not in full detail, the outline of project

    public void GetSetSchdulerTime(string DropDownListValueTime)
    {
    Timer timScheduledTask = new Timer();
    timScheduledTask.Interval = DropDownListValueTime * 60 * 1000;
    
    timScheduledTask.Elapsed += new System.Timers.ElapsedEventHandler(timScheduledTask_Elapsed);
    
    timScheduledTask.Enabled = true;
    }
    
    
      public void timScheduledTask_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
            {
        FirstTaskGenerateExcel();
                } 
    
      public void FirstTaskGenerateExcel()
            {
                // Here is the code we need to execute periodically
               ////some code
            }
    
    
    }
    

    Here the parameter DropDownListValueTime I am changing to one minute to two minute , the timer is doing for every one minute as well two minute, how to cancel previous event after passing other value in timer


    R L Kiran

    Wednesday, July 11, 2018 4:07 PM