Introduction

In this article we will see how to use Timer class in .NET Framework under System.Timers namespace. The example is made of C# use under Console Application. Often we need to schedule our task like need for an event to be triggered at various absolute time. For example every 24 hour, everyday at certain time etc. We can achieve this in various way like using Windows Task Scheduler. But here we will see how we can use Timer class in .NET Framework to achieve this scheduled job. This sample illustrates a way to let user to know how they can schedule a task using timer.

 Return to Top



What is timer?

According to MSDN documentation Generates an event after a set interval, with an option to generate recurring events. So, the Timer allows us to set a time interval to periodically execute an event at a specified interval. It is useful when we want to execute certain functions/applications after a certain interval.

The C# timer event keeps track of time just like a clock would, it is basically an accessible clock and counts in milliseconds, thousandths of a second. This allows for great detail.

Code structure inside the timer:

private void timer1_Tick(object sender, EventArgs e)
{
  //events occur when timer stops
  timer.Stop();
  Console.WriteLine("Hello World!!!"); //Code to Perform Task goes in between here
  timer.Start();
}

 Return to Top



Type of Timer in .NET Framework

The .NET Framework Class Library provides following different timer classes:

  • System.Windows.Forms.Timer (Windows-based timer)
  • System.Timers.Timer (Server-based timer)
  • System.Threading.Timer (Thread timer)
  • System.Web.UI.Timer (Web-based timer)
  • System.Windows.Threading.DispatcherTimer (Thread timer)

Each of these classes has been designed and optimized for use in different situations. This article describes System.Timers.Timer class and helps you gain an understanding of how this class should be used. To know more about other timer class please look into here.

 Return to Top



Schedule a Task

Scheduling a task in code this term means any code that does something, causes something to happen, and has action to it. Example:
  • Making an object appear
  • Making an object move
  • Fire any event
  • Trigger functions

Timer counts automatically. When the timer counts down the amount of time set in the preferences, it executes whatever code is in it, then it automatically restarts and counts down again.


Basic Functions

Some of the functions that is used in this project.

  • Timer.Enabled: "Whether the Timer should raise the Elapsed event." This must set this to true if we want timer to do anything.
  • Timer.Interval: Interval of the time is count in milliseconds, between raisings of the Elapsed event. The default is 100 milliseconds." We must make this interval longer than the default. For example, for 60 seconds or 1 minute, use 60000 as the Interval.
  • Timer.Start: This does the same thing as setting Enabled to true. Starts raising the Elapsed event by setting Enabled to true.
  • Timer.Stop: This does the same thing as setting Enabled to false. Stops raising the Elapsed event by setting Enabled to false.
  • Timer.Tick: Occurs when the specified timer interval has elapsed and the timer is enabled.
  • Timer.Elapsed: This is the event that is invoked each time the Interval of the Timer has passed.

Code Usage


using System;
using System.Timers;
 
namespace ScheduleTimer
{
    class Program
    {
        static Timer timer;
 
        static void Main(string[] args)
        {
            schedule_Timer();
            Console.ReadLine();
        }
 
        static void schedule_Timer()
        {
            Console.WriteLine("### Timer Started ###");
 
            DateTime nowTime = DateTime.Now;
            DateTime scheduledTime = new DateTime(nowTime.Year, nowTime.Month, nowTime.Day, 8, 42, 0, 0); //Specify your scheduled time HH,MM,SS [8am and 42 minutes]
            if (nowTime > scheduledTime)
            {
                scheduledTime = scheduledTime.AddDays(1);
            }
 
            double tickTime = (double)(scheduledTime - DateTime.Now).TotalMilliseconds;
            timer = new Timer(tickTime);
            timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
            timer.Start();
        }
 
        static void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            Console.WriteLine("### Timer Stopped ### \n");
            timer.Stop();
            Console.WriteLine("### Scheduled Task Started ### \n\n");
            Console.WriteLine("Hello World!!! - Performing scheduled task\n");
            Console.WriteLine("### Task Finished ### \n\n");
            schedule_Timer();
        }
    }
}


Output




Explanation

As you can see when timer hit the specified interval it stops and starts performing the given task, for our case just simply print "Hello World" on the console window.

If we look closer we can see that a timer object is created, then we assigned the interval in millisecond by calculating current time with scheduled time. Then we assign the associated method the timer will execute after interval.

Then Start method is called to start the interval. The timer continues to operate until it hit the specified interval. When it hit the specified interval Stop method is called to stop the timer, perform the specified task, after completing start the timer again.

Two DateTime object is created. Once is for the current date time and other is for to detecting scheduled date time. Also our code has the ability to automatically increment it's date to next day to perform the task daily. So, no user interaction needed.

 Return to Top



Summary

We looked at the Timer class from the System.Timers namespace in .NET Framework. One point we may want to consider when working with timers is whether our problem can be solved more simply by using the Windows Scheduler to run a standard executable periodically. Here timer is used to fires off a program at a given time. We could also use timer in following cases:

  • Fire off a program at a given time
  • Display the time on the screen
  • Create a backup routine that copies important data at a given interval
  • Can create a routine to automatically log off a user or end a program after a given time period with no activity
  • Create a WCF service add timer to schedule a job

Beside these numerous ways timer can be used.

 Return to Top



Reference

  • Timer class under System.Timers namespace here
  • All about .NET Timers - A Comparison here
  • Introduction to Server-Based Timers here
  • Timers, Timer Resolution, and Development of Efficient Code here

 Return to Top



See Also

 Return to Top



Download

You can download the Source Code used in the example from this link Download Source Code

 Return to Top



web analytics