articles

Home / DeveloperSection / Articles / Timer in C#

Timer in C#

AVADHESH PATEL 19037 18-Sep-2012
Timers often play an important role in both client applications and server-based components (including Windows services). Writing effective timer-driven managed code requires a clear understanding of program flow and the subtleties of the .NET threading model. The .NET Framework Class Library provides three different timer classes: System.Windows.Forms.Timer, System.Timers.Timer, and System.Threading.Timer. Each of these classes has been designed and optimized for use in different situations. This article examines the three timer classes and helps you gain an understanding of how and when each class should be used.
Types of Timer

 1.       System.Windows.Forms.Timer

 2.       System.Timers.Timer

 3.       System.Threading.Timer

System.Windows.Forms.Timer 

System.Windows.Form.Timer a timer that raises an event at user-defined intervals. This timer is optimized for use in Windows Forms applications and must be used in a window.

A Timer is used to raise an event at user-defined intervals. This Windows timer is designed for a single-threaded environment where UI threads are used to perform processing. It requires that the user code have a UI message pump available and always operate from the same thread, or marshal the call onto another thread.

When you use this timer, use the Tick event to perform a polling operation or to display a splash screen for a specified period of time. Whenever the Enabled property is set to true and the Interval property is greater than zero, the Tick event is raised at intervals based on the Interval property setting.

This class provides methods to set the interval, and to start and stop the timer.  

using System;

using System.Windows.Forms;

namespace Timer
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        static System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();
        static int alarmCounter = 1;
        static bool exitFlag = false;
        private void btnTimer_Click(object sender, EventArgs e)
        {
            /* Adds the event and the event handler for the method that will
          process the timer event to the timer. */
            myTimer.Tick += new EventHandler(TimerEventProcessor);
            // Sets the timer interval to 5 seconds.
            myTimer.Interval = 5000;
            myTimer.Start();
            // Runs the timer, and raises the event.
            while (exitFlag == false)
            {
                // Processes all the events in the queue.
                Application.DoEvents();
            }
        }

        private static void TimerEventProcessor(Object myObject,  EventArgs myEventArgs)
        {
            myTimer.Stop();
            // Displays a message box asking whether to continue running the timer.
            if (MessageBox.Show("Continue running?", "Count is: " + alarmCounter,  MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                // Restarts the timer and increments the counter.
                alarmCounter += 1;
                myTimer.Enabled = true;
            }
            else
            {
                // Stops the timer.
                exitFlag = true;
            }
        }
    }
}
Output 

Timer in C#

Timer in C#

System.Timers.Timer 

The Timer component is a server-based timer, which allows you to specify a recurring interval at which the Elapsed event is raised in your application. You can then handle this event to provide regular processing. For example, suppose you have a critical server that must be kept running 24 hours a day, 7 days a week. You could create a service that uses a Timer to periodically check the server and ensure that the system is up and running. If the system is not responding, the service could attempt to restart the server or notify an administrator.

The server-based Timer is designed for use with worker threads in a multithreaded environment. Server timers can move among threads to handle the raised Elapsed event, resulting in more accuracy than Windows timers in raising the event on time.

The Timer component raises the Elapsed event, based on the value of the Interval property. You can handle this event to perform the processing you need. For example, suppose that you have an online sales application that continuously posts sales orders to a database. The service that compiles the instructions for shipping operates on a batch of orders rather than processing each order individually. You could use a Timer to start the batch processing every 30 minutes.

using System;
using System.Timers; 
namespace SystemTimersTimer
{     class Program
    {         private static System.Timers.Timer aTimer; 
        static void Main(string[] args)
        { 
            // Normally, the timer is declared at the class level,
            // so that it stays in scope as long as it is needed.
            // If the timer is declared in a long-running method, 
            // KeepAlive must be used to prevent the JIT compiler
            // from allowing aggressive garbage collection to occur
            // before the method ends. You can experiment with this             // by commenting out the class-level declaration and
            // uncommenting the declaration below; then uncomment
            // the GC.KeepAlive(aTimer) at the end of the method.
            //System.Timers.Timer aTimer; 
            // Create a timer with a ten second interval.
            aTimer = new System.Timers.Timer(10000); 
            // Hook up the Elapsed event for the timer.
            aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); 
            // Set the Interval to 2 seconds (2000 milliseconds).
            aTimer.Interval = 2000;
            aTimer.Enabled = true;
            Console.WriteLine("Press the Enter key to exit the program.");
            Console.ReadLine(); 
            // If the timer is declared in a long-running method, use
            // KeepAlive to prevent garbage collection from occurring
            // before the method ends.
            //GC.KeepAlive(aTimer);
        }
 
        private static void OnTimedEvent(object source, ElapsedEventArgs e)
        {
            Console.WriteLine("The Elapsed event was raised at" + e.SignalTime);
        }
    }
}
Output

Timer in C#

System.Threading.Timer 

Provides a mechanism for executing a method at specified intervals. This class cannot be inherited.

Use a TimerCallback (Initializes a new instance of the Timer class with an infinite period and an infinite due time, using the newly created Timer object as the state object.) delegate to specify the method you want the Timer to execute. The timer delegate is specified when the timer is constructed, and cannot be changed. The method does not execute on the thread that created the timer; it executes on a ThreadPool thread supplied by the system.

When you create a timer, you can specify an amount of time to wait before the first execution of the method (due time), and an amount of time to wait between subsequent executions (period). You can change these values, or disable the timer, using the Change (Changes the start time and the interval between method invocations for a timer, using 32-bit signed integers to measure time intervals.) method.

When a timer is no longer needed, use the Dispose (Releases all resources used by the current instance of Timer.) method to free the resources held by the timer. Note that callbacks can occur after the Dispose() method overload has been called, because the timer queues callbacks for execution by thread pool threads. You can use the Dispose (WaitHandle) (Releases all resources used by the current instance of Timer and signals when the timer has been disposed of.) method overload to wait until all callbacks have completed.

The callback method executed by the timer should be reentrant, because it is called on ThreadPool threads. The callback can be executed simultaneously on two thread pool threads if the timer interval is less than the time required executing the callback or if all thread pool threads are in use and the callback is queued multiple times.

using System;
using System.Threading;
 
namespace SystemThreadingTimer
{
    class TimerExampleState
    {         public int counter = 0;
        public Timer tmr;
    } 
    class Program
    {
        static void Main(string[] args)
        {
            TimerExampleState s = new TimerExampleState(); 
            // Create the delegate that invokes methods for the timer.
            TimerCallback timerDelegate = new TimerCallback(CheckStatus); 
            // Create a timer that waits one second, then invokes every second.
            Timer timer = new Timer(timerDelegate, s, 1000, 1000); 
            // Keep a handle to the timer, so it can be disposed.
            s.tmr = timer;
            // The main thread does nothing until the timer is disposed.
            while (s.tmr != null)
                Thread.Sleep(0);
            Console.WriteLine("Timer example done.");
        }
        // The following method is called by the timer's delegate. 
        static void CheckStatus(Object state)
        {
            TimerExampleState s = (TimerExampleState)state;
            s.counter++;
            Console.WriteLine("{0} Checking Status {1}.", DateTime.Now.TimeOfDay, s.counter);
            if (s.counter == 5)
            {
                // Shorten the period. Wait 10 seconds to restart the timer.
                (s.tmr).Change(10000, 100);
                Console.WriteLine("changed...");
            }
            if (s.counter == 10)
            {
                Console.WriteLine("disposing of timer...");
                s.tmr.Dispose();
                s.tmr = null;
            }
        }
    }
}

 Output 

Timer in C#



c# c# 
Updated 14-Jul-2020
Avadhesh Kumar Patel District Project Manager - Aligarh 14 months work experience in Panchayati Raj Department Sector as District Project Manager & 12 months work experience in IT Sector as Software Engineer. :-)

Leave Comment

Comments

Liked By