Home > other >  C# executing if statement every 10 seconds
C# executing if statement every 10 seconds

Time:07-12

I want my code (messagebox) to run no sooner than 10 seconds in this loop timer which is 2000 milliseconds. Is that possible. I want the if statement to be executed every 10 seconds or more but not less even though the loop is 2 seconds.

 public void InitBrowser()
        {
        Timer t = new Timer();
        t.Interval = 2000;
        t.Tick  = new EventHandler(timer_Tick);
        t.Start();
        }

        void timer_Tick(object sender, EventArgs e)
        {
        mycode();
        }

        public async void mycode()
        {
            DateTime SOMETIME = DateTime.Today;
            if (DateTime.Now.Subtract(SOMETIME).TotalSeconds > 10)
            {
                          MessageBox.Show("RUNNED");
            }
        }

CodePudding user response:

As mentioned in comments, the cleanest way to do this would be to use a timer that ticks every 10 seconds, even if that means having to create a separate one from the timer used by other code.

If you absolutely must do it this way, however, you need to keep state (i.e. an instance field) which either keeps track of when you last ran the code, or when you should next run it, or how long it's been since you've run it. If you want to keep using DateTime, you should use DateTime.UtcNow rather than DateTime.Now, otherwise you could well end up with problems around daylight saving time boundaries. Even with DateTime.UtcNow you can end up with problems due to the system clock updating - using a Stopwatch to keep track of the elapsed time since the last run is probably a better bet. So the code would look something like:

public class WhateverYourClassIsCalled
{
    private static readonly TimeSpan ExecutionInterval = TimeSpan.FromSeconds(10);

    // TODO: Rename to something more meaningful (we don't know what the code does)
    private readonly Stopwatch stopwatch;

    public void InitBrowser()
    {
        stopwatch = Stopwatch.StartNew();
        Timer t = new Timer { Interval = 2000 };
        t.Tick  = (sender, args) => HandleTimerTick();
        t.Start();
    }

    // TODO: Avoid async void if possible
    private async void HandleTimerTick()
    {
        if (stopwatch.Elapsed >= ExecutionInterval)
        {
            stopwatch.Restart();
            // Execute your code here
        }
        // Other code here
    }
}

CodePudding user response:

Just override SOMETIME when condition is pass. If statement pass next time in more than 10 seconds

E: end move declaration to class field

  •  Tags:  
  • c#
  • Related