Search code examples
c#timersystem.timers.timer

Running a function at random intervals C#


I have this function below that I call on my constructor:

 public void IntervalSC()
 {
     Random rnd = new Random();
     double interval = rnd.Next(2000, 6000);
     var SCTimer = new System.Timers.Timer();
     SCTimer.Elapsed += new ElapsedEventHandler(dashboardController.Screenshot);
     SCTimer.Interval = interval;
     SCTimer.Enabled = true;
 }

I want the interval to run dashboardController.Screenshot between 2000 and 6000 but after the random number is generated, it doesn't change and keeps running the Screenshot function at a fixed interval generated by rnd. I understand that it's because IntervalSC() is ran once so the random number for the interval is generated only once too. So I'm looking for suggestions on how to make this work, running dashboardController.Screenshot at random intervals. Thank you.


Solution

  • You could edit the timer inside dashboardController.Screenshot but I feel it's cleaner to add another handler to do that. For example:

    private Random rnd = new Random();
    
    void Main()
    {
        double interval = rnd.Next(2000, 6000);
        var SCTimer = new System.Timers.Timer();
        SCTimer.Elapsed += new ElapsedEventHandler(dashboardController.Screenshot);
        SCTimer.Elapsed += new ElapsedEventHandler(ChangeTimerInterval);
        SCTimer.Interval = interval;
        SCTimer.Enabled = true;
    }
    
    public void ChangeTimerInterval(Object source, System.Timers.ElapsedEventArgs e)
    {
        var timer = source as System.Timers.Timer;
        
        timer.Interval = rnd.Next(2000, 6000);
    }