Bits & Bytes

Creating Timer Events in C#

If you want something to happen in a C# program at regular time intervals, the ideal way is to create a callback function that makes use of the Timer class. Below, I have created a class called CTimedObject that holds a Timer object. In the constructor, the Timer is allocated with a time interval of 2000 milliseconds or 2 seconds. Then OnTimedEvent() is set as a callback using the += operator and the Elapsed property. Finally, The Timer is started via a call to Start().

At this point, OnTimedEvent() will be called every 2 seconds. Inside the OnTimedEvent() function, the time is written to the console window via the passed in event object of type ElapsedEventArgs. The Object that is passed in is the Timer. Executing the program, the output looks like this

TimerEvent

Program.cs

using System;
using System.Timers;

namespace UsingTimers {
    class Program {
        static void Main(string[] args) {
            CTimedObject qTimedObject = new CTimedObject();
            Console.WriteLine("Press the Enter key to exit the program... ");
            Console.ReadLine();
        }
    }
}

CTimedObject.cs

using System;
using System.Timers;

namespace UsingTimers {
    class Program {
        static void Main(string[] args) {
            Timer qTimer = new Timer(2000);
            qTimer.Elapsed += OnTimedEvent;
            qTimer.Start();
            Console.WriteLine("Press the Enter key to exit the program... ");
            Console.ReadLine();
        }

        static private void OnTimedEvent(Object qTimer, ElapsedEventArgs eElapsed) {
            Console.WriteLine(eElapsed.SignalTime);
        }
    }
}

The code above demonstrates how to use a Timer in an object. Alternatively, we could do the same thing more simply if we just want the event to fire with a static function. Below, we have code that does exacly the same thing without using a separate class.

Program.cs

using System;
using System.Timers;

namespace UsingTimers {
    public class CTimedObject {

        Timer mqTimer = null;

        public CTimedObject() {
            mqTimer = new Timer(2000);
            mqTimer.Elapsed += OnTimedEvent;
            mqTimer.Start();
        }

        private void OnTimedEvent(Object qTimer, ElapsedEventArgs eElapsed) {
            Console.WriteLine(eElapsed.SignalTime);
        }
    }
}

Tags: , , , , , , , , , , ,

Michael Hall

By: Michael Hall

Leave a Reply

*

 

© 2007–2024 XoaX.net LLC. All rights reserved.