user10722652
user10722652

Reputation: 23

How can I run my Timer forever in asp.net?

In ASP.NET I want to run my timer forever (as long as my host server is running). How can I achieve this?

public int ClickCount
{
        get
        {
            object o = ViewState["ClickCount"];
            return (o == null) ? 0 : (int)o;
        }
        set
        {
            ViewState["ClickCount"] = value;
        }
    }

    public int minute
    {
        get
        {
            object o = ViewState["minute"];
            return (o == null) ? 0 : (int)o;
        }
        set
        {
            ViewState["minute"] = value;
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        if (minute < 5)
        {
            if (ClickCount < 5)
            {
                ClickCount++;
                MsgBox("node inserted", this.Page, this);
            }
            else
            {
                MsgBox("not more than 5 nodes in 5 minutes", this.Page, 
this);
            }
        }
        else
        {
            minute = 0;
            ClickCount = 0;
        }
    }

    protected void Timer1_Tick(object sender, EventArgs e)
    {
        minute = minute + 1;
    }

<asp:Timer ID="Timer1" runat="server" Interval="60000" 
           ontick="Timer1_Tick">
</asp:Timer>

According to me my variable "minute" well be incremented by 1 after every timer_tick event. But problem is that my timer will be close when i stop my application. And as you says that I can use host server system clock, then how can I use it. I mean to say that how I can code my application so that at every host server system clock pulse my variable "minute" will be incremented by 1. Thanks.

Upvotes: 0

Views: 276

Answers (1)

John Wu
John Wu

Reputation: 52210

To start your "timer," store the current time.

void StartTimer()
{
    ViewState["StartTime"] = DateTime.Now;
}

When you wish to obtain a value for minutes, calculate it:

int Minutes 
{
    get
    {
        DateTime startTime = (DateTime)ViewState["StartTime"];
        TimeSpan elapsed = DateTime.Now - startTime;
        return elapsed.TotallMinutes;
    }
}        

There is no need to actually increment anything, or keep a timer of your own.

You could also render the startTime value into a hidden HTML field, which would allow Javascript to display the timer by performing a similar calculation. The advantage of JS would be continuous updating.

Upvotes: 2

Related Questions