HowTo: Time-controlled & recurrent functions in .NET & ASP.NET

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 ]

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

About the author

Written by Code Inside Team

Currently there is no additional info about this author.

4 Responses

  1. You wrote Threat.Sleep :)

    Reply
  2. @Danny Thanks man. I fixed it :)

    Reply
  3. Greetings I recently finished reading through your blog as well as I´m very impressed. I really do have a couple inquiries for you personally however. Do you think you´re thinking about doing a follow-up publishing about this? Will you be gonna keep bringing up-to-date at the same time?

    Reply
  4. I just came across your page, but i just wanted to say i truly enjoyed your post, thanks.

    Reply

Comment on this post

Recent Posts

  • Automated Security Analyser for ASP.NET websites

    Evil Hackers are lurking everywhere and many Web-applications are delicately and share “too much” with the attacker. A quick (first!) overview offers the Tool “ASafaWeb”. All the website does is making a few requests and writing an Analyses including problem solving’s. There are no permanent disadvantages (bad requests/ DoS attacks and so on). Example: KnowYourStack.com ...

  • image1489-570x194.png
    „Sign in with Twitter“ for your own ASP.NET WebApp

      “Sign in with Twitter” is a popular practice to authenticate the users on your website. One advantage compared to an own registration is the lower inhibition for the user. But on the other hand Twitter doesn’t fess up with all the information’s and you will get into a kind of addiction. At the end ...

  • image1485-570x194_thumb.png
    CodePlex is going to be updated

      CodePlex the Microsoft Open Source Project Hosting Plattform hasn’t changed that much in the last few years and for a few times I thought Microsoft stopped the whole developing process. But now I found out that there is still life in the project. Maybe it is because of the success of GitHub or because ...

  • image1474_thumb.png
    What does Adobe in the flash-free web? Magazine-Style Layouts with CSS Regions!

      Adobe is well known for Photoshop and Flash but of course there is a lot more. According to the “Future Post” from Google Adobe declared one of their big subjects on a Blogpost. I’m talking about the W3C Working Draft to CSS Regions. Adobe cooperates with the WebKit Team and W3C on this. What ...

  • image1471-523x194.png
    HTML 5 Games, Tooling & 3D

      Game Developing is an interesting subject for all kind of software developer. But as a web developer without any Flash-skills there aren’t that much starting points. With HTML5 and the combination between Javascript, CSS3 and fast browsers there are the first “robust” HTML5 games. HTML5 games? Is this real? Neowin created a “Top 10” ...

Support us