C# 如何运行计时器 10 分钟然后禁用按钮?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18282260/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:48:01  来源:igfitidea点击:

How can I run a timer for 10 minutes and then disable the button?

c#asp.netbuttontimer

提问by user2684131

I took help from :http://forum.codecall.net/topic/65434-c-working-with-timers/(in it a decremented counter is used, but it's not working in my app)

我得到了帮助:http: //forum.codecall.net/topic/65434-c-working-with-timers/(其中使用了递减计数器,但它在我的应用程序中不起作用)

I have some text field and two buttons: submit and update. I have implemented a timer from toolbar to update button.

我有一些文本字段和两个按钮:提交和更新。我已经实现了从工具栏到更新按钮的计时器。

I wanted this timer to run for 10 minutes and then disable the update button. But presently it's running for just 2 minutes.

我希望这个计时器运行 10 分钟,然后禁用更新按钮。但目前它只运行了 2 分钟。

Buttons Code:

按钮代码:

<asp:Button ID="Btnsave" runat="server" CssClass="bt3dbuttons" 
    onclick="Btnsave_Click" OnClientClick="return confirm('Data Submitted')" 
    Text="Submit" Width="77px" />

<asp:Timer ID="Timer2" runat="server" ontick="Timer2_Tick">
</asp:Timer>
<asp:Button ID="Butnupdate" runat="server" CssClass="btupbuttons" 
    onclick="Btnupdate_Click" Text="Update" visible="false" Width="85px" />

Here is the code for timer:

下面是定时器的代码:

private System.Timers.Timer aTimer = new System.Timers.Timer(600000)
                                                { AutoReset = false };
protected void Timer2_Tick(object sender, EventArgs e)
{    
   aTimer = new System.Timers.Timer(600000);
   aTimer.Interval = 600000;
   double counter = aTimer.Interval;

   counter++;
   if (counter >= 600000)
   {    
       Butnupdate.Enabled = false;
       MessageBox.Show("Time Up!");
   }
}

Code for Update Button:

更新按钮代码:

protected void Btnupdate_Click(object sender, EventArgs e) 
{

    string id = Id.Text.Trim();
    string name = Name.Text;
    string project = Project.Text;
    string result = Total.Text;

    using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["CM_Connection"].ConnectionString))
    {
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;

        try
        {
            //lets check that the user typed the first number
            if (Viva.Text.Length > 1)
            {
                VivaLabel.Text = "Please enter a valid number to add.";
                return;
            }

            //lets check that the user typed the second number
            else if (Presentation.Text.Length > 1)
            {
                PresentationLabel.Text = "Please enter a valid number to add.";
                return;
            }
            else if (Confidence.Text.Length > 1)
            {
                ConfidenceLabel.Text = "Please enter a valid number to add.";
                return;
            }

            else if (System.Text.Length > 1)
            {
                SystemLabel.Text = "Please enter a valid number to add.";
                return;
            }
            //Now we have valid inputs
            //Lets put them into integer values

            int number1 = int.Parse(Viva.Text);
            int number2 = int.Parse(Presentation.Text);
            int number3 = int.Parse(Confidence.Text);
            int number4 = int.Parse(System.Text);
            //Now lets add the numbers
            int total = number1 + number2 + number3 + number4;

            //lets place it into the TextBox3
            Total.Text = total.ToString();

            //  cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = @"UPDATE Result SET Name = @name, Project = @project, Result = @result WHERE ID = @id";
            con.Open();

            cmd.Parameters.AddWithValue("@id", Id.Text.ToString());
            cmd.Parameters.AddWithValue("@name ", Name.Text.ToString());
            cmd.Parameters.AddWithValue("@project ", Project.Text.ToString());
            cmd.Parameters.AddWithValue("@result ", Total.Text.ToString());
            cmd.ExecuteNonQuery();
        }

        catch (Exception ex1)
        {
            //Report error to user in the bottom Label
            MessageBox.Show(ex1.Message);
        }
    }
}

采纳答案by user2684131

Problem has been solved by following code:

问题已通过以下代码解决:

Create the timer ( default can be used from toolbox) set the timer interval property

创建计时器(默认可以从工具箱中使用)设置计时器间隔属性

<asp:Timer ID="Timer2" runat="server" ontick="Timer2_Tick" 
            Interval="600000">
        </asp:Timer>

For reference see: http://msdn.microsoft.com/en-us/library/system.web.ui.timer.interval.aspx

参考:http: //msdn.microsoft.com/en-us/library/system.web.ui.timer.interval.aspx

Create the event handler for timer :

为 timer 创建事件处理程序:

protected void Timer2_Tick(object sender, EventArgs e)
        {

            if (timeLeft > 0)
            {
                // Display the new time left 
                // by updating the Time Left label.
                timeLeft = timeLeft - 1;
                Label1.Text = timeLeft + " seconds";
            }
            else
            {
                // If the user ran out of time, stop the timer, show 
                // a MessageBox, and fill in the answers.
                Timer2.Enabled = false;
                Label1.Text = "Time's up!";
                MessageBox.Show("You didn't finish in time.", "Sorry");

                Butnupdate.Enabled = false;
            }

use the following in the button on which you want your timer to start:

在您希望计时器启动的按钮中使用以下内容:

timeLeft = 600;
                    Label1.Text = DateTime.Now.ToString("HH:mm:ss tt");
                    Timer2.Enabled = true;

If you want to show the current system time or current time use

如果要显示当前系统时间或当前时间使用

Label1.Text = DateTime.Now.ToString("HH:mm:ss tt");

I declared it into label and how to do it and above please have a look here: http://msdn.microsoft.com/en-us/library/dd492144.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2

我将其声明为标签以及如何执行及以上操作,请查看此处:http: //msdn.microsoft.com/en-us/library/dd492144.aspx?cs-save-lang=1&cs-lang=csharp#代码片段 2

Here we go a timer to disable button after 10 minutes :) Hopes it helps somebody as well :)

在这里,我们使用计时器在 10 分钟后禁用按钮 :) 希望它也能帮助某人 :)

回答by Karl Anderson

Your timer may be getting garbage collected if it is a long-running method instead of as part of the class, I cannot tell by the code posted.

如果您的计时器是长时间运行的方法而不是作为类的一部分,则它可能会被垃圾收集,我无法通过发布的代码判断。

Read the Timer.Interval Propertydocumentation, which also has a sample of how to implement a timer.

阅读Timer.Interval 属性文档,其中还提供了如何实现计时器的示例。

回答by OnoSendai

According to the System.Timers.Timer class documentation, it fires up an event once the the defined time is elapsed, in an asynchronous way.

根据 System.Timers.Timer 类文档,一旦定义的时间过去,它就会以异步方式触发一个事件。

The setup code would look like this:

设置代码如下所示:

        var aTimer = new System.Timers.Timer(10 * 60 * 1000);
        aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
        aTimer.Enabled = true;

And the event itself like this:

事件本身是这样的:

    private static void OnTimedEvent(object source, ElapsedEventArgs e)
    {
        //Do your event management here.
    }

Hope it works for you.

希望对你有效。

回答by Mauricio Gracia Gutierrez

Use this code as a guide

使用此代码作为指南

public class Timer1
{
    private static System.Timers.Timer aTimer;

    public static void Main()
    {
        // Create a timer with a ten second interval.
        aTimer = new System.Timers.Timer(600000);

        // Hook up the Elapsed event for the timer.
        aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

        // Set the Interval to 10 minutes 
        aTimer.Interval = 600000;
        aTimer.Enabled = true;

        Console.WriteLine("Press the Enter key to exit the program.");
        Console.ReadLine();

        // If the timer is declared in a long-running method, use 
        // KeepAlive to prevent garbage collection from occurring 
        // before the method ends. 
        GC.KeepAlive(aTimer);
    }

    // Specify what you want to happen when the Elapsed event is  
    // raised. 
    private static void OnTimedEvent(object source, ElapsedEventArgs e)
    {
        Butnupdate.Enabled = false;
        MessageBox.Show("Time Up!");
    }
}

Example taken from

示例取自

http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx

http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx

回答by Mesh

Set the Interval Property of the asp:Timer this will then postback the page and call the ontick handler

设置 asp:Timer 的 Interval 属性,这将回发页面并调用 ontick 处理程序

<asp:Timer ID="Timer2" runat="server" ontick="Timer2_Tick" Interval="60000">
        </asp:Timer>

http://msdn.microsoft.com/en-us/library/system.web.ui.timer.interval.aspx

http://msdn.microsoft.com/en-us/library/system.web.ui.timer.interval.aspx

I'm not sure what you are trying to do with the System.Timers.Timeron the server code it wont get used unless you page processing takes an extraordinary long time.

我不确定您要System.Timers.Timer对服务器上的代码做什么,除非您的页面处理需要非常长的时间,否则它不会被使用。