简体   繁体   English

如何在 asp.net 中永远运行我的定时器?

[英]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).在 ASP.NET 中,我想永远运行我的计时器(只要我的主机服务器正在运行)。 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.根据我的说法,我的变量“分钟”在每个 timer_tick 事件之后都会增加 1。 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.我的意思是说我如何编码我的应用程序,以便在每个主机服务器系统时钟脉冲我的变量“分钟”将增加 1。谢谢。

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:当您希望获得minutes的值时,请计算它:

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.您还可以将startTime值渲染到隐藏的 HTML 字段中,这将允许 Javascript 通过执行类似的计算来显示计时器。 The advantage of JS would be continuous updating. JS 的优势在于不断更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM