C# create a timer loop which runs code every 30 minutes?

Toby picture Toby · Apr 26, 2013 · Viewed 32.5k times · Source

I would like to input an autosave feature in my C# program which will run a line of code at the end of the countdown, then restart the countdown. It will run my SaveFile(); function.

I would like this timer to be started when the user first saves/opens the document, and have it disabled if they open a new document.

Answer

Pierre-Luc Pineault picture Pierre-Luc Pineault · Apr 26, 2013

You can use the Elapsed event on the System.Timers Timer.

Timer timer = new Timer(30 * 60 * 1000);
timer.Elapsed += OnTick; // Which can also be written as += new ElapsedEventHandler(OnTick);


private void OnTick(object source, ElapsedEventArgs e)
{ 
    //Save logic
}

And don't forget to call timer.Start() when you need it.