Bits & Bytes

Posts Tagged ‘timer’

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);
        }
    }
}

Creating a Timed Callback Function in Actionscript 3.0

Below, we have an example program, which creates a timer callback function. This program draws a circle that flashes in the middle of the screen at a rate that is specified by the timer that we create. The code sets a timer to call a function that, alternatively, adds and removes a circle from the objects that are to be displayed.

The first three lines of active code initialize the Timer. The first line creates an instance of a Timer that creates a TIMER event every 1000 milliseconds, which equals 1 second. The second line sets the function FlashCircle() to get called every time a TIMER event occurs. The third line starts the Timer so that it generates events every second.

// Create a 1 second timer
var qMyTimer:Timer = new Timer(1000);
qMyTimer.addEventListener(TimerEvent.TIMER, FlashCircle);
qMyTimer.start();

var bDrawCircle:Boolean = true;

// Create a sprite with a circle drawn on it.
var qCircle:Sprite = new Sprite();
var uiColor:uint = 0x00800000;
qCircle.graphics.beginFill(uiColor);
    qCircle.graphics.drawCircle(160, 120, 100);
qCircle.graphics.endFill();

function FlashCircle(e:TimerEvent):void {
    // Add or remove the circle from the stage
    if (bDrawCircle) {
        addChild(qCircle);
    } else {
        removeChild(qCircle);
    }
    // Alternate the drawing
    bDrawCircle = !bDrawCircle;
}

Once the timer is initialized, we have a Boolean, bDrawCircle, that is used to toggle the display of the circle. Below this, we create a Sprite and draw a dark red circle on it. The circle is located at (160, 120) and has a radius of 100.

Finally, we have the callback function FlashCircle(). This function is called every second via a TIMER event. Inside the function, we add or remove the Sprite with the circle drawn on it from the list of items to be displayed. The last line reverses the value of the Boolean, bDrawCircle, to alternate it value between true and false and toggle the drawing of qCircle.

var qMyTimer:Timer = new Timer(1000, 3);

The timer in the program runs continuously. We could set the second argument in the constructor to 3, as shown in the line above. With this constructor call, the timer only runs 3 seconds and generates 3 events. When we don’t specify a second argument, the default value of 0 is used, which sets the timer to run indefinitely.

When we have a finite number of events coming from the timer, we can set an event callback to run when the timer is completely finished. The event TimerEvent.TIMER_COMPLETE can be used instead of TimerEvent.TIMER for a callback that runs when the timer is completely finished.