Executing method on a certain interval + offset I would like to execute a certain method at a given interval. The reason why I can't use a timer + its event handler right away is because I want to add an offset to each tick (100ms in my example below).

It seems to be working just as intented. The reason why I'm starting it manually is because if the _action(); takes more than the given tick time, I want to let it finish before starting a new "tick".

Perhaps this could be done in a much simpler way. I would like your thoughts on the code:

class RandomIntervalTask : IDisposable
{
    private readonly Timer _timer;
    private readonly int _initialInterval;
    private readonly int _range;
    private readonly Action _action;

    public RandomIntervalTask(int initialInterval, int range, Action action)
    {
        this._range = range;
        this._initialInterval = initialInterval;
        this._action = action;

        _timer = new Timer { AutoReset = false, Interval = initialInterval };
        _timer.Elapsed += TimerElapsed;
        _timer.Start();
    }

    private void TimerElapsed(object sender, ElapsedEventArgs e)
    {
        var rnd = new Random();

        _timer.Interval = rnd.Next(_initialInterval, _initialInterval + _range);
        _action();
        _timer.Start();
    }

    public void Dispose()
    {
        _timer.Stop();
        _timer.Dispose();
    }
}


Executed like this:

var rit = new RandomIntervalTask(400, 100, DoStuff);

private void DoStuff()
{
    Debug.WriteLine("stuff");
}
Do not put the random number generator creation in the TimerElapsed method. This could wind up generating the same value if called in succession rapidly. Instead put it at the class level:

private readonly Random _rnd = new Random();


and change appropriately in the method.