【问题标题】:C# How to run code at given time? [closed]C#如何在给定时间运行代码? [关闭]
【发布时间】:2013-08-16 09:01:49
【问题描述】:

简单来说,

我早上开始运行我的 C# 程序,该程序应该在下午 5:45 向用户显示一条消息。如何在 C# 中做到这一点?

编辑:我问这个问题是因为我认为使用计时器不是最好的解决方案(定期比较当前时间与我需要运行任务的时间):

private void timerDoWork_Tick(object sender, EventArgs e)
{
    if (DateTime.Now >= _timeToDoWork)
    {

        MessageBox.Show("Time to go home!");
        timerDoWork.Enabled = false;

    }
}

【问题讨论】:

  • 您应该提供您尝试解决问题的代码示例。
  • 下午 5:45 设置Timer
  • 您误解了Timer 类,最好再次查看文档。

标签: c#


【解决方案1】:

我问这个问题是因为我认为使用计时器不是最好的解决方案(定期比较当前时间与我需要运行任务的时间)

为什么?为什么不定时最好的解决方案? IMO 计时器是最好的解决方案。但不是您实施的方式。请尝试以下操作。

private System.Threading.Timer timer;
private void SetUpTimer(TimeSpan alertTime)
{
     DateTime current = DateTime.Now;
     TimeSpan timeToGo = alertTime - current.TimeOfDay;
     if (timeToGo < TimeSpan.Zero)
     {
        return;//time already passed
     }
     this.timer = new System.Threading.Timer(x =>
     {
         this.ShowMessageToUser();
     }, null, timeToGo, Timeout.InfiniteTimeSpan);
}

private void ShowMessageToUser()
{
    if (this.InvokeRequired)
    {
        this.Invoke(new MethodInvoker(this.ShowMessageToUser));
    }
    else
    {
        MessageBox.Show("Your message");
    }
}

这样使用

 SetUpTimer(new TimeSpan(17, 45, 00));

【讨论】:

  • 在 .NET 4+ 中使用:TimeSpan InfiniteTimeSpan = new TimeSpan(0, 0, 0, 0, -1);而不是 Timeout.InfiniteTimeSpan
【解决方案2】:

你也可以使用Task Scheduler

还有一个Timer 课程可以帮助你

【讨论】:

    【解决方案3】:

    您可以轻松实现自己的警报类。首先,您可能需要查看 MS 文章末尾的 Alarm class

    【讨论】:

      【解决方案4】:

      如果 DateTime.Now ==(您想要的具体时间),您可以使用 Timer 检查每一分钟

      这是一个带有 windows 窗体的代码示例

      public MainWindow()
          {
              InitializeComponent();
              System.Windows.Threading.DispatcherTimer timer_1 = new System.Windows.Threading.DispatcherTimer();
              timer_1.Interval = new TimeSpan(0, 1, 0);
              timer_1.Tick += new EventHandler(timer_1_Tick);
              Form1 alert = new Form1();
          }
          List<Alarm> alarms = new List<Alarm>();
      
          public struct Alarm
          {
              public DateTime alarm_time;
              public string message;
          }
      
      
          public void timer_1_Tick(object sender, EventArgs e)
          {
              foreach (Alarm i in alarms) if (DateTime.Now > i.alarm_time) { Form1.Show(); Form1.label1.Text = i.message; }
          }
      

      【讨论】:

      • 为什么要检查每一分钟?我们不能将计时器设置为所需的时间吗?
      • 我认为最好使用滴答事件处理程序创建一个间隔为 1 分钟(例如)的计时器,以使程序每分钟检查一次是否对应。如果您想设置多个“警报”,之后会容易得多。
      • 我不这么认为,看看我的解决方案stackoverflow.com/a/18270238/2530848
      • 我的意思是,如果你想设置多个闹钟,你将为每个闹钟创建一个计时器,另一方面,我承认检查也会变得更重,你的事情越多'必须检查
      • 每个闹钟没有一个计时器,我将设置第一个闹钟时间,当该事件过去时,我会将相同的计时器设置为下一个间隔。这样做我们可以重用计时器并避免每秒检查
      猜你喜欢
      • 2019-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-09
      • 1970-01-01
      相关资源
      最近更新 更多