26 September 2010 HowTo, Timer, Timers, Zeit CI Team

image

During a project we had the order to run a specific SQL request after several minutes or seconds and to evaluate them in order to the results. You can solve this problem a little bit "dirty" by using a while(true) loop and Thread.Sleep, or you use a timer.

Example:

For example we are going to build a console application which is used to write something on the commando line every 10 seconds.

The "Dirty" way..

    while (true)
            {
                Thread.Sleep(1000);
                Console.WriteLine("Bla!");
            }

This alternative works but it isn´t very classy. And especially if you are planning to do two or three things in order you are going to have a problem.

.NET Framework Timer

Particularly for this problem there are several classes of timer in .NET Framework. An older MSDN Articel describes three different types:

At the end of the article there is a really good comparison:

image

In my opinion the "System.Windows.Forms.Timer" is only useful for Windows.Forms applications.

Interesting is the difference between "System.Timers.Timer" and "System.Threading.Timer"

The Timer in "Threading" namespace is without any additional work not thread safe.The System.Timers.Timer is based on the System.Threading.Timer. However for easy applications the System.Timers.Timer is a good choice. Here you can find a little  Stackoverflow-Discussion.

Using System.Timers.Timer

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Timers;

namespace Timers.ConsoleApp
{

    class Program
    {

        static void Main(string[] args)
        {
            Timer timer = new Timer();
            timer.Interval = 1000;
            timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
            timer.Enabled = true;

            Console.ReadLine();
        }

        static void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            Console.WriteLine("Elapsed!");
        }
    }
}

According to the interval the conformable Event is opened. A Thread is taken from the Threadpool.

Another alternative : AutoResetEvent

For me a totally unknown class till today: AutoResetEvent

  AutoResetEvent _isStopping = new AutoResetEvent(false);
            TimeSpan waitInterval = TimeSpan.FromMilliseconds(1000);

            for (; !_isStopping.WaitOne(waitInterval); )
            {
                Console.WriteLine("Bla!");
            }

In Fact it looks like the whole while(true) story and I´m sure it also works equal.

Other alternatives you will found on the Stackoverflow-discussion .

Timer in ASP.NET applications

In my example I talked about a console application but am it possible to create this for an ASP.NET application as well? Yes and No.

Stackoverflow found out a little trick to implement a "background job".Easy Background Tasks in ASP.NET

The Trick works by laying down an item into the cache for a specific time. When the time runs out an event will be created. In this event the time-controlled action will be started and you have to lay down a new item into the cache and so on...

The Problem: usually the IIS Process is going to shut down after a while and then you can´t go on working with it.

So many alternatives. And now?

image

Like already mentioned, the easiest solution is the System.Timers.Timer. While working with ASP.NET I would like to recommend you to not use time-controlled applications because you never know when the AppPool is going to shut down. It´s better to use the timer in a windows service. But if there is no other way you better try one of the other alternatives I presented to you.

Probably there exist a lot more alternatives. How are you solving any time-controlled problems? Of course you can solve it with a Sheduled Task or a program for consoles but that isn´t very classy as well. Aren´t it? ;)

[ Download Democode ]