C#如何在给定时间内运行的代码? [英] C# How to run code at given time?

查看:215
本文介绍了C#如何在给定时间内运行的代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要简单地说,



我开始运行在早上我的C#程序,该程序应显示在用户的消息在下午5:45。我怎样才能做到这在C#



编辑:我问这个问题,因为我想用一个定时器是不是最好的解决方案(周期性比较当前的时间的时候,我需要运行的任务):

 私人无效timerDoWork_Tick(对象发件人,EventArgs五)
{
如果(DateTime.Now> = _timeToDoWork)
{

MessageBox.Show(时间回家!);
timerDoWork.Enabled = FALSE;

}
}


解决方案

我问这个问题,因为我想用一个定时器是不是最好的解决方案(周期性比较当前的时间,我需要运行任务的时间)


< /块引用>

为什么呢?为什么不定时器A最好的解决办法? IMO定时器是最好的解决方案。但不是你的方式已经实现。试试以下

 私人System.Threading.Timer定时器; 
私人无效SetUpTimer(时间跨​​度alertTime)
{
DateTime的电流= DateTime.Now;
时间跨度timeToGo = alertTime - current.TimeOfDay;
如果(timeToGo< TimeSpan.Zero)
{
的回报;已经通过
//时间}
this.timer =新System.Threading.Timer(X = GT;
{
this.ShowMessageToUser();
},空,timeToGo,Timeout.InfiniteTimeSpan);
}

私人无效ShowMessageToUser()
{
如果(this.InvokeRequired)
{
this.Invoke(新MethodInvoker(这.ShowMessageToUser));
}
,否则
{
MessageBox.Show(您的信息);
}
}

使用像这样

  SetUpTimer(新的TimeSpan(17,45,00)); 


To put it simply,

I start running my C# program in the morning, and the program should show the user a message at 5:45 PM. How can I do this in C#?

Edit: I asked this question because I thought using a timer is not the best solution (comparing the current time periodically to the time I need to run the task):

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

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

    }
}

解决方案

I asked this question because I thought using a timer is not the best solution (comparing the current time periodically to the time I need to run the task)

Why? why not timer a best solution? IMO timer is the best solution. but not the way you have implemented. Try the following.

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");
    }
}

Use it like this

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

这篇关于C#如何在给定时间内运行的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆