程序运行时,在设定的时间调用方法?

时间:2014-02-24 18:13:18

标签: c#

我试图找到一些代码,如果程序正在运行,将在13:00运行一个方法

我使用C sharp并创建一个窗体

我开始使用timer设置为1分钟,而当timer_tick我尝试if statement尝试

if (TimeDate.Now == new DateTime(0001, 01, 01, 08, 00)) 

干杯

1 个答案:

答案 0 :(得分:0)

使用System.Threading.Timers.Timer对象;

从你所需时间的下一个实例开始运行计时器,之后每24个运行一次。

// TimerCallback object that wraps your method to call when timer elapses 
// (see end of answer)
var tc = new TimerCallback(DoStuffAt1300Hours);

// Tomorrow 2/25/14 at 1pm
var dt = new DateTime(2014, 2, 25, 13, 0, 0);

// dt - DateTime.Now = start timer in whatever time is between now and tomorrow at 1pm
// This is a delay, so effectively, the timer will start tomorrow at 1pm
// And it will run every 24 hours, calling the method DoStuffAt1300Hours()
var timer = new Timer(tc, null, dt - DateTime.Now, TimeSpan.FromHours(24));

创建一个将执行您想要的回调;

public static void DoStuffAt1300Hours(object o)
{
    Console.WriteLine("Hey it's 1pm!");
}