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.

8 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
  5. Find out issues i may come up with!…Amazing! We appreciate you offering this!

    Reply
  6. Hey it really is myself as soon as once more, simply questioning if there is an excellent rss feed i could sign up for?! Truly taking into consideration mastering a lot far more about this.

    Reply
  7. You’ve got made it genuinely crystal clear and simple to verify out

    Reply
  8. Our views may possibly possibly get altered, even though not the truth that Now i’m appropriate.

    Reply

Comment on this post

Recent Posts

  • Windows Phone Fonts & what if Visual Studio lies

    Today I was confronted with a little Problem: my Windows Phone App refused to show me the Font I choose – also other thinks didn’t work. Although the Visual Studio Designer did show the Fonts: Unfortunately there isn’t much left in the Emulator: Reason for this: Windows Phone doesn’t include all the typos Windows does ...

  • Json-Online-Tools: Viewer & Json2Csharp generator

      Wherever APIs are mentioned the JSON format I not far away. Since I’m using two tools regularly I would like to introduce you to them. JSON Viewer If you only see the JSON-Text you are usually not able to see the structure. With the help of JSON Viewer you can have an easy overview: ...

  • Windows Phone SDK & „System“-Icons

      Although the Metro Design focuses a lot on Typography Icons are still quite important. If you install Windows Phone SDK you will receive 36 Icons. You can find them here: C:\Program Files (x86)\Microsoft SDKs\Windows Phone\v8.0\Icons Unfortunately many Icons you might know from the common applications are not integrated. Pedro Lamas extracted 99 additional Icons ...

  • image1830-570x194.png
    How can I figure out if my ADFS 2.0 works?

      I was working with ADFS 2.0 (“Active Directory Federation Services”) for a while when this simple question crossed my mind: How can I figure out if the connection between ADFS and AD “works”? Here is a simple test… What is ADFS? If you need some “position of trusts” beneath the AD-boarders you choose an ...

  • Subdomain vs. Subdirectory

      Better blog.mydomain.com or mydomain.com/blog? Good question! If got asked this question again via Twitter on the weekend so therefore I decide to share my experiences:   Choose a subdomain, if…. - You plan to offer “different services” which are “logical separated” on one domain - You are able to influence the subdomains without much ...

Support us