Link to home
Start Free TrialLog in
Avatar of tantormedia
tantormediaFlag for United States of America

asked on

Where instantiate System.Threading.Timer

Dear experts,

I want to use System.Threading.Timer. My question is, where should I instantiate it to start ticking? I probably want to do it only once, and not on each Page_Load().
I trued to do it like this:
    private readonly System.Threading.Timer tpsTimer = new System.Threading.Timer(CheckForPastDue, null, 10000, 5000);
on my page (rather, MasterPage), but it didn't work as the CheckForPastDue method is not static.
Thanks.
Avatar of raterus
raterus
Flag of United States of America image

What do you need a timer for?  You might have much better luck with the javascript "setTimeout" function.  Due to the stateless nature of web pages, I don't see how a server side time object will do anything meaningful for you.
Avatar of tantormedia

ASKER

I want the timer to call a method that checks if some items are past due, and if there are any, to send email notifications.
I cannot use PageMethod as it has to be static, which I don't want.
ASKER CERTIFIED SOLUTION
Avatar of raterus
raterus
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi,

Try it in Global.asax.

Regards,
VSS

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Threading;

namespace TestNet4
{
    public class Global : System.Web.HttpApplication
    {
        void Application_Start(object sender, EventArgs e)
        {
            private readonly System.Threading.Timer tpsTimer = new System.Threading.Timer(CheckForPastDue, null, 10000, 5000);
        }

        void Application_End(object sender, EventArgs e)
        {
            //  Code that runs on application shutdown

        }

        void Application_Error(object sender, EventArgs e)
        {
            // Code that runs when an unhandled error occurs

        }

        void Session_Start(object sender, EventArgs e)
        {
            // Code that runs when a new session is started

        }

        void Session_End(object sender, EventArgs e)
        {
            // Code that runs when a session ends. 
            // Note: The Session_End event is raised only when the sessionstate mode
            // is set to InProc in the Web.config file. If session mode is set to StateServer 
            // or SQLServer, the event is not raised.

        }

    }   

}

Open in new window

vs00saini,

Thank you for your answer. But my manager just said it should not be connected to my asp.net application, but has to be a separate program.
Thank you for your help. I will also go with a Console application using System.Threading.Timer.