在Asp.Net C#中每20秒按一次按钮就会发生事件

时间:2016-02-24 20:55:19

标签: c# asp.net datetime

一旦我点击一个按钮,我就会尝试每天都有一个特定的动作,但是为了测试目的,我试图让它每20秒发生一次,只是为了看它是否有效。目前,没有任何反应,我不知道我哪里出错了。

  public void AddIncoming_Click(object sender, EventArgs e)
    {
        if (frequencyIncoming.SelectedValue == "Weekly")
        {
            DateTime weekly = DateTime.Now;
            for (DateTime current = weekly; current == current.AddSeconds(20);)
            {
                //totalCalculation = (totalCalculation + Convert.ToDouble(costIncoming));
                ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + DateTime.Now + "');", true);
            }

        }

        SqlCommand cmd = new SqlCommand("insert into Incomings (AspNetUsersId,IncType,IncDate,IncCost,IncFrequency) values (@AspNetUsersId, @IncType, @IncDate, @IncCost, @IncFrequency)");

        cmd.Parameters.AddWithValue("@AspNetUsersId", userId);
        cmd.Parameters.AddWithValue("@IncType", typeIncoming.Text);
        cmd.Parameters.AddWithValue("@IncDate", lblCalendar.Text);
        cmd.Parameters.AddWithValue("@IncCost", costIncoming.Text);
        cmd.Parameters.AddWithValue("@IncFrequency", frequencyIncoming.Text);

        loadDatabase(cmd);

        Response.Redirect(Request.Url.AbsoluteUri);

    }

非常感谢任何信息! 干杯

1 个答案:

答案 0 :(得分:0)

编辑:实际上,只是执行此操作(如果您可以检测到程序正在关闭,可能会设置一些逻辑来设置“keepLo​​oping = false”):

public void AddIncoming_Click(object sender, EventArgs e)
{
    if (frequencyIncoming.SelectedValue == "Weekly")
    {
        DateTime weekly = DateTime.Now;
        TimeSpan timeToWait = new TimeSpan(0, 0, 0, 5); // days, hours, minutes, seconds
        bool keepLooping = true;
        while (keepLooping)
        {
            if (DateTime.Now.Subtract(weekly) < timeToWait)
            {
                //sleep 1 second while waiting so cpu doesn't spin at maximum
                System.Threading.Thread.Sleep(1000);
            }
            else
            {
                // this code will run every ~timeToWait
                Console.WriteLine($"{DateTime.Now.Subtract(weekly)} seconds have elapsed.");
                weekly = DateTime.Now;
            }
        }
    }

    SqlCommand cmd = new SqlCommand("insert into Incomings (AspNetUsersId,IncType,IncDate,IncCost,IncFrequency) values (@AspNetUsersId, @IncType, @IncDate, @IncCost, @IncFrequency)");

    cmd.Parameters.AddWithValue("@AspNetUsersId", userId);
    cmd.Parameters.AddWithValue("@IncType", typeIncoming.Text);
    cmd.Parameters.AddWithValue("@IncDate", lblCalendar.Text);
    cmd.Parameters.AddWithValue("@IncCost", costIncoming.Text);
    cmd.Parameters.AddWithValue("@IncFrequency", frequencyIncoming.Text);

    loadDatabase(cmd);

    Response.Redirect(Request.Url.AbsoluteUri);

}