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 ]

Read more

HowTo: Facebook Connect & ASP.NET MVC

Facebook has created a nice little service named "Facebook Connect". With this application Facebook user are allowed to login into your site with their usual facebook log-in information´s and the whole thing is secured by Facebook. In Fact it´s quite similar to OpenID but it had some more specials than just identification. But in this […]

Read more

HowTo: Cross Domain Ajax with JSONP and ASP.NET

Actually it isn´t possible to send Ajax Requests to addresses which are reachable at the same domain like the site where the script is executed.The reason for this is the Same Origin Policy in JavaScript. There it is given, that the port, the protocol and the domain have to be equal to start requests. This […]

Read more

HowTo: Introduction in to MetaWebLog API

This Blogspot is based on Scott Hanselmans “WeeklySourceCode”, where MetaWebLog API was the subject of today. In the Blogspot he relates that MS use the Windows Live Writer also to administrate their own websites. The tool is absolutely practical and it works with MetaWebLog API. With this tool it´s possible to create “CMS” Content with […]

Read more

Windows 7 RC Training Kit for Developer

Microsoft released the Training Kit for developer yesterday. It contains presentations, Hands on Labs and democode for the new Windows 7 APIs. The Traing Kit is directed towards to C++ developers, but Microsoft offers Wrapper classen for .NET. Topics: Taskbar Libraries Multi Touch Sensors and Location Ribbon Trigger Start Services, Instrumentation and ETW Application Compatability […]

Read more

Visual Studio 2010 & .NET Framework 4 Training Kit – May Preview

Microsoft released a preview Training Kit for .NET 4.0 & VS 2010: Download. It includes 28 presentations, 13 demos & 16 Hands-on Labs.   Overview The Visual Studio 2010 and .NET Framework 4 Training Kit includes presentations, hands-on labs, and demos. This content is designed to help you learn how to utilize the Visual Studio […]

Read more

Inside Microsoft’s home of the future

Microsoft shows in a Video how the “home of the future” might look like. Some photos of this house could be found here. Speak recognition & “NUI“s are “key features” in this house.  

Read more

Free eBook: Practical .NET Unit Testing

Nice intro to unit testing (& mocking) with .NET: – Practical .NET Unit Testing

Read more

Free eBook: Testing Chapter from Beginning ASP.NET MVC

Just found an interesting eBook: – Free Chapter of Beginning ASP.NET MVC 1.0 – Testing ASP.NET MVC Applications (Blogpost)

Read more

HowTo: Create RSS Feeds with Linq to XML / XLinq

It´s very easy to create an RSS using Linq to XML. In my sample I create a ASP.NET page, which offers a RSS Feed. We add also a meta tag so that users can find our RSS Feed.     Project structure: To let the user know that we offer a RSS Feed we create […]

Read more

Recent Posts

  • image2021-570x194_thumb.png
    HowTo: Create RSS Feeds with ASP.NET MVC

    I’ve already written about how to consume RSS or Atom Feeds with the SyndicationFeed (in German, sry) but todays post is about how to create or publish an own feed. Beside the age of the feed standard and the much defamation from Facebook, Twitter and Google on RSS/Atom I consider this easy to consume API […]

  • image1997-311x194_thumb.png
    How to access an Azure Website with the local IIS Manager

    Since the end of February it is possible to access an Azure Website with the IIS Manager. Although the Azure Management site offers some information there are more details visible at the IIS Manager. For the connection you will need an IIS Manager and the IIS Manager for Remote Administration Extension. It’s also possible to […]

  • image1929-570x143_thumb.png
    Create and validate own Json-Web-Tokens (JWTs)

    If you are interested in web authentication you probably have heard about JSON Web tokens (JWT). What is a JWT? Maybe I’m not using the correct security termination but however: JWTs are used to exchange claims between two systems. For example: You want to log on to a service (like Facebook, Twitter, etc.) and want […]

  • Micro-Optimization: how to shrink or „embed“ pictures

      I’m currently working on the “CodeInside Dashboard” and since the page structure isn’t that difficult it should be possible to fulfill all of Google Pagespeed or Yahoos YSlow recommendations. One of the rules was to optimize the 4 PNGs that are embedded on the page.   Before – without optimization: Below you can see […]

  • image1979-570x194.png
    Move to Windows Azure – VMs, Word Press Migration, DNS changes

    Since mid January this blogs runs on a WordPress installation in an Azure VM. Because I always thought that the subject is quite complicated this blogpost offers a view behind the scenes. Why this move? So far this blog (both German and English Version) runs on a hoster somewhere in Germany. The main problem with this […]

Support us