Search code examples
c#if-statementdlltimer

How to create a timer that starts on a certain condition, and counts to 15 seconds? (C#)


I am creating a C# library, and am looking to create a timer that starts once a certain condition is met. Then, I want the timer to count up to 15 seconds, and once 15 seconds is reached, another action is performed. It would look something like this:

if (condition is met)
{
    //start timer
}

if (timer == 15 seconds)
{
    //do something
    //reset timer for next time that condition is met
}

Any help on how to do this in C# is greatly appreciated!


Solution

  • //using System.Timers;
    

    How to insitantiate:

    Timer timer = new Timer(); //Outside the method
    

    Inside the method that the timer subscribes

    timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
    timer.Interval = 15000; //number in milisecinds  
    timer.Enabled = true;
    

    The OnElapsedTime EventHandler

    private async void OnElapsedTime(object source, ElapsedEventArgs e)
    {
        //Do Something
    }
    

    Notes:

    1. It is important to using System.Timers;
    2. The event will run every 15000 (15 seconds)
    3. Code inside the event handler will be executed automatically (not need for condition).