xxxxxxxxxx
using System;
using System.Threading;
public static class Program {
public static void Main() {
// Create a Timer object that knows to call our TimerCallback
// method once every 2000 milliseconds.
Timer t = new Timer(TimerCallback, null, 0, 2000);
// Wait for the user to hit <Enter>
Console.ReadLine();
}
private static void TimerCallback(Object o) {
// Display the date/time when this method got called.
Console.WriteLine("In TimerCallback: " + DateTime.Now);
// Force a garbage collection to occur for this demo.
GC.Collect();
}
}
xxxxxxxxxx
public static void Main()
{
System.Timers.Timer aTimer = new System.Timers.Timer();
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = 5000;
aTimer.Enabled = true;
Console.WriteLine("Press \'q\' to quit the sample.");
while(Console.Read() != 'q');
}
// Specify what you want to happen when the Elapsed event is raised.
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
Console.WriteLine("Hello World!");
}
xxxxxxxxxx
using System;
using System.Timers;
class Program
{
static Timer timer;
static void Main(string[] args)
{
// Create a timer with a 1 second interval
timer = new Timer(1000);
// Hook up the Elapsed event
timer.Elapsed += OnTimerElapsed;
// Start the timer
timer.Enabled = true;
// Wait for user input to exit
Console.ReadLine();
}
static void OnTimerElapsed(object sender, ElapsedEventArgs e)
{
// This method will be called every second
Console.WriteLine("Tick");
}
}
create a static Timer object and set its interval to 1000 milliseconds (1 second). We also hook up an event handler to the Elapsed event of the timer. Finally, we start the timer and wait for user input to exit the program.
The OnTimerElapsed method is called every second, and in this example, we simply output the string "Tick" to the console. You can replace this with your own code to perform whatever task you need to execute on a timer.
xxxxxxxxxx
using System;
using System.Timers;
class Program
{
static Timer timer;
static void Main(string[] args)
{
// Create a Timer object with a 1 second interval
timer = new Timer(1000);
// Hook up the Elapsed event
timer.Elapsed += OnTimerElapsed;
// Start the timer
timer.Start();
Console.WriteLine("Timer started. Press any key to stop...");
Console.ReadKey();
// Stop the timer
timer.Stop();
Console.WriteLine("Timer stopped. Press any key to exit.");
Console.ReadKey();
}
static void OnTimerElapsed(object sender, ElapsedEventArgs e)
{
// This method will be called each time the timer interval elapses
Console.WriteLine("Timer elapsed at: " + DateTime.Now);
}
}