Search code examples
c#.nettimer

Execute a function ever 60 seconds


I want to execute a function every 60 seconds in C#. I could use the Timer class like so:

timer1 = new Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 60 * 1000; // in miliseconds
timer1.Start();

Question is I have a long running process. Occasionally it make take several minutes. Is there a way to make the timer smart so if the function is already being executed then it should skip that cycle and come back 60 seconds later and if again it is in execution then again skip and come back 60 seconds later.


Solution

  • I would suggest you to have a class member variable bool variable with value false.

    then in click event return if its true at the beginning.

    and then set it to true, so that it will tell you that its currently in execution.

    then write your logic.

    and then once done finally set it to false again.

    code will look like this.

    private bool isRunning = false;
    
    private void timer1_Tick(object sender, EventArgs e)
    {
        if (isRunning)
        {
            return;
        }
    
        isRunning = true;
        
        try
        {
            ... //Do whatever you want 
        }
        finally
        {
            isRunning = false;
        }
    }