Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save geoffreymcgill/84981360f1de36ab0057749e3da23d66 to your computer and use it in GitHub Desktop.
Save geoffreymcgill/84981360f1de36ab0057749e3da23d66 to your computer and use it in GitHub Desktop.
// We need the Timer reference to have access to it in the callback
public static Timer timer;
// A flag of changing the Timer's due time and period
public static bool timerChanged;
public static void Main()
{
// The Timer callback
TimerCallback callback = (state) =>
{
// We passed the stopwatch to the Timer's constructor
// So, we can access it within the callback
Stopwatch stopwatch = state as Stopwatch;
var seconds = stopwatch.Elapsed.Seconds;
Console.WriteLine(seconds);
if (!App.timerChanged && seconds >= 5 && seconds < 10)
{
App.timerChanged = true;
// Changes the Timer's due time and period
timer.Change(2000, 2000);
}
if (seconds >= 10)
{
// Stops and disposes the Timer
App.timer.Dispose();
Console.WriteLine("The Timer has been disposed.");
}
};
// The stopwatch to monitor the executions of the callback
var sw = new Stopwatch();
sw.Start();
// The amount of time to wait before the first execution of the callback
var dueTime = 0;
// The amount of time to wait between subsequent executions of the callback
var period = 1000;
// We should keep the reference to the Timer,
// to be able to access within the callback
App.timer = new Timer(callback, sw, dueTime, period);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment