Return to Snippet

Revision: 19820
at November 6, 2009 08:54 by rtipton


Updated Code
using System;
using System.Threading;

class Program
{
    static void Main()
    {
        AutoResetEvent reset = new AutoResetEvent(false);
        StatusChecker status = new StatusChecker(5);

        // Invoke methods for the timer via a Delegate
        TimerCallback timerDelegate = new TimerCallback(status.CheckStatus);

        // Create a timer that signals the delegate to invoke 
        // Check status after one second, and then every 1/4 second
        Console.WriteLine("{0} Creating the timer.\n",DateTime.Now.ToString("h:mm:ss.fff"));
        Timer stateTimer = new Timer(timerDelegate, reset, 1000, 250);

        // When the auto reset executes, change to every 1/2 second
        reset.WaitOne(5000, false);
        stateTimer.Change(0, 500);
        Console.WriteLine("\nChanging the timer period.\n");

        reset.WaitOne(5000, false);
        stateTimer.Dispose();
        Console.WriteLine("\nDestroying the timer.");
    }
}

class StatusChecker
{
    int invokeCount, maxCount;

    public StatusChecker(int count)
    {
        invokeCount = 0;
        maxCount = count;
    }

    // This method is called by the timer delegate.
    public void CheckStatus(Object stateInfo)
    {
        AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
        Console.WriteLine("{0} Checking status {1,2}.",
            DateTime.Now.ToString("h:mm:ss.fff"),
            (++invokeCount).ToString());

        if (invokeCount == maxCount)
        {
            // Reset the counter and signal Main.
            invokeCount = 0;
            autoEvent.Set();
        }
    }
}

Revision: 19819
at October 31, 2009 22:34 by rtipton


Initial Code
using System;
using System.Timers;

public class Program
{
    private static System.Timers.Timer testTimer;

    public static void Main(string[] args)
    {
        testTimer = new System.Timers.Timer(5000); // 5 seconds
        testTimer.Elapsed += new ElapsedEventHandler(OnTimerElapsed);

        testTimer.Interval = 5000;
        testTimer.Enabled = true;

        Console.WriteLine("Press the enter key to stop the timer");
        Console.ReadLine();

    }

    private static void OnTimerElapsed(object source, ElapsedEventArgs e)
    {
        Console.WriteLine("Timer elapsed at {0}", e.SignalTime);
    }
}

Initial URL


Initial Description


Initial Title
System.Threading.Timer Example

Initial Tags


Initial Language
C#