开发者

System.Timers.Timer not working every 5 minutes

I have a method which must be run every 5minutes in order to show latest data in gridview.

I was experimenting with System.Timers.Timer and the following is my code:

 protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            lblError.Text = "";

            t = new System.Timers.Timer(300000);//every 5min = 300000
            t.Enabled = true;
            t.Elapsed += new ElapsedEventHandler(t_Elapsed);

            if (!Page.IsPostBack)
            {
                //t = new System.Timers.Timer(300000);//every 5min = 300000
                //t.Enabled = true;
                //t.Elapsed += new ElapsedEventHandler(t_Elapsed);

                floor = ddFloors.SelectedValue.ToString();
                GenerateStatus();
            }
        }
        catch (Exception ex)
        {
            lblError.Text = ex.Message; 
        }
    }


  void t_Elapsed(object sender, ElapsedEventArgs e)
    {
        try
        {
            //Response.Redirect("Home.aspx");
            floor = ddFloors.SelectedValue.ToString();
            GenerateStatus();
        }
        catch (Exception ex)
        {开发者_开发问答
            lblError.Text = ex.Message;
        }
    }

the problem is that after 5minutes it is not going to t_Elapsed. Note this should keep being done at all times not just for once. any help pls?


Set your timer's AutoReset member to true

You can read more about AutoReset on MSDN.

Actually true is the default for AutoReset, likely your problem is that your response is sent and your timer goes out of scope.


You need to better understand the client/server model of web applications. By the time this event fires the page has long since been rendered and sent to the browser.
If you want to do something like this you will have to do it on the client using javascript. A combination of a jQuery plugin like jQuery timers and using an AJAX call back to the server should help you achieve what you want.


Your timer is a local variable and so it goes out of scope.

Also, this is an ASP.NET page and creating Timers on the server is not a very good idea.

Is the regular event something that needs to happen on the server only, or do you want it to do something in the users browser?

If you want a recurring event to happen on the server, see this blog post about scheduling recurring events in ASP.NET:

https://blog.stackoverflow.com/2008/07/easy-background-tasks-in-aspnet/

If you want the recurring event to have some effect in the users browser, you need to use Javascript and/or JQuery to trigger the event from the client side rather than on the server


what you need is to do refresh in the clientside, the server function just run once when the page load,use meta or settimeout

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜