Skip to content

Instantly share code, notes, and snippets.

@miroslavradojevic
Last active August 2, 2018 09:25
Show Gist options
  • Save miroslavradojevic/61102a1581fdba965a8b63940441a770 to your computer and use it in GitHub Desktop.
Save miroslavradojevic/61102a1581fdba965a8b63940441a770 to your computer and use it in GitHub Desktop.
Timer triggers some action every 500ms and can be stopped or started with button press.
namespace TimerElapsed
{
using System;
using System.Timers;
public class Program
{
static Timer myTimer;
static void Main(string[] args)
{
myTimer = new Timer();
myTimer.Elapsed += OnMyTimerElapsed;
myTimer.Interval = 500;
myTimer.AutoReset = true;
myTimer.Enabled = false;
Console.WriteLine("\nStart(): {0}", DateTime.Now);
Console.WriteLine("Usage:\n" +
"a: start timer\n" +
"b: stop timer\n" +
"c: print current timer state (enabled, elapsed)\n" +
"ESC, Ctrl+C to exit\n");
ConsoleKeyInfo keyinfo;
do
{
keyinfo = Console.ReadKey();
if (keyinfo.Key == ConsoleKey.A)
{
Console.WriteLine($"\nEnable and start timer {DateTime.Now}");
myTimer.Enabled = true;
myTimer.Start();
}
if (keyinfo.Key == ConsoleKey.B)
{
Console.WriteLine($"\nDisable and stop timer {DateTime.Now}");
myTimer.Enabled = false;
myTimer.Stop();
}
if (keyinfo.Key == ConsoleKey.C)
{
Console.WriteLine($"\ntimer status: enabled={myTimer.Enabled}");
}
}
while (keyinfo.Key != ConsoleKey.Escape);
}
private static void OnMyTimerElapsed(object source, ElapsedEventArgs e)
{
Console.ForegroundColor = ConsoleColor.DarkYellow;
Console.WriteLine($"\nelapsed {DateTime.Now}");
Console.ResetColor();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment