Home > Net >  In ASP.NET web application, in which method do I implement a timer that calls a function every 5 min
In ASP.NET web application, in which method do I implement a timer that calls a function every 5 min

Time:08-19

I have an ASP.NET Web application, in the .aspx.cs file, I have to call a function called RefreshData() every 10 minutes that basically updates the Gridview, Gridvew1 using Databind().

In the PageLoad method I have some code that is supposed to call RefreshData() every 5 minutes using a timer but it doesn't seem to work

aTimer = new System.Timers.Timer();
        aTimer.Interval = 1000 * 300;

        aTimer.Elapsed  = OnTimedEvent;

        // Have the timer fire repeated events (true is the default)
        aTimer.AutoReset = true;

        // Start the timer
        aTimer.Enabled = true;


    }

    protected void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
    {
        RefreshData();
        Label3.Text = "The Elapsed event was raised at "   e.SignalTime.ToString();
    }

Since there's no Main() method, where can this timer be implemented?

Thanks.

CodePudding user response:

You want as a general rule to avoid timer type things in a web page.

Keep in mind that the values, and code behind ONLY exists during the short page post back. Once the web page is send to the client, then the web page, the variables in code, and EVERYTHING is dumped and goes out of memory. The web server is now waiting for ANY page from ANY user - not just your web page which is now gone out of scope. the code behind is gone - VERY much like calling a function, and upon return, the function you just called is now gone. You have to think of web pages like that. You might have 10 users --- but you ONLY have ONE web server that can process a page from that user.

So RIGHT after your page is send to the client side? Then ALL OF your server side code is GONE - OUT of scope! - DOES NOT exist anymore!!!

So, the most easy way to get a timer going is to have the web page post-back at your desired time interval. This will HAVE to occur at the browser side level. This means you roll up your sleeves and write JavaScript, or you can use some built in tools that does the same thing (there is a browser side timer control you can thus use for this purpose).

So, you can't have some timer code in that code behind page, since the page DOES NOT exist anymore!!! The page, the code, the variables? They are ALL gone RIGHT after the page travels down to the client's browser. On the server side, your page page code is dumped - gone, does not exist anymore!

this is why we call web development state-less. The code and page after running goes OUT of scope. As I stated, a great way to think of this is when you call a function, and the function exits - the code and values in the function call are now gone. Think of your whole web page this way - it goes out of scope once the post-back and round trip is done. You don't have a desktop for each user, but ONE web server that has to process ANY page from ANY user. Each web page and that code thus does not exist anymore once the page event and processing is done, and the page is sent back to client side.

So, say we have this grid:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
    DataKeyNames="ID" CssClass="table table-hover" width="40%">
    <Columns>
        <asp:BoundField DataField="FirstName" HeaderText="FirstName"  />
        <asp:BoundField DataField="LastName" HeaderText="LastName"  />
        <asp:BoundField DataField="HotelName" HeaderText="HotelName" />
        <asp:BoundField DataField="City" HeaderText="City"  />
        <asp:BoundField DataField="Description" HeaderText="Description"  />

        <asp:TemplateField HeaderText="" ItemStyle-HorizontalAlign="Center">
            <ItemTemplate>
                <button id="cmdDelete" runat="server"  
                    onserverclick="cmdDelete_ServerClick" >
                    <span aria-hidden="true" > Delete</span> 
                </button>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

And code to load is this:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            LoadGrid();
    }

    void LoadGrid()
    {
        string strSQL = @"SELECT * FROM tblHotelsA ORDER BY HotelName";
        using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
        {
            using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
            {
                conn.Open();
                DataTable rstData = new DataTable();
                rstData.Load(cmdSQL.ExecuteReader());
                GridView1.DataSource = rstData;
                GridView1.DataBind();
            }
        }
    }

And we now have this:

enter image description here

Ok, so now we want this gv to refresh say every 8 minutes.

So, in your web page, drop in a script manager, and then drop in a timer control.

We have this:

enter image description here

Now, go to events on the timer, and choose this:

enter image description here

(you can double click in that on tick event, the code behind stub will be created.

so, now we have this:

    protected void Timer1_Tick(object sender, EventArgs e)
    {
        LoadGrid();
    }

So, that code stub will now trigger every 8 minutes

(8 x 60 = 840 x 1000)

The time you specify is every 1000 milliseconds (so 1000 = 1 second).

  • Related