C#如何在一天中的特定时间触发事件?

And*_*rei 5 c# events triggers timer

我正在开发一个程序,需要在一天的某个小时删除一个文件夹(然后重新实例化),这个小时将由用户给出.

小时很可能是在夜间,因为没有人访问该文件夹(它在工作时间以外).有没有办法在某个时刻触发该事件?

我知道计时器,但有没有一个更简单的方法来做这个没有计时器,嘀嗒和检查,看看它是什么时间?

编辑:也许我不够具体.我想触发一个方法来做某事,而不必先在一个单独的可执行文件中编译它.此方法是作为Windows服务实现的更大类的一部分.所以这项服务会持续运行,但是在一天中的某个时间,它应该触发此功能来删除该文件夹.

谢谢.

Ode*_*ded 8

打破常规思考问题.

不需要在这种工作上编码 - 使用计划任务,他们已经在Windows中使用了很长时间.你可以从这开始你的程序.

更新 :(更新后的问题)

如果需要从已经运行的服务触发方法,请使用计时器并DateTime.Now根据目标时间进行测试.


Cat*_*lMF 5

如果要在代码中执行此操作,则需要使用Timer类并触发Elapsed事件。

A.计算直到您的第一个运行时为止的时间。

TimeSpan day = new TimeSpan(24, 00, 00);    // 24 hours in a day.
TimeSpan now = TimeSpan.Parse(DateTime.Now.ToString("HH:mm"));     // The current time in 24 hour format
TimeSpan activationTime = new TimeSpan(4,0,0);    // 4 AM

TimeSpan timeLeftUntilFirstRun = ((day - now) + activationTime);
if(timeLeftUntilFirstRun.TotalHours > 24)
    timeLeftUntilFirstRun -= new TimeSpan(24,0,0);    // Deducts a day from the schedule so it will run today.
Run Code Online (Sandbox Code Playgroud)

B.设置计时器事件。

Timer execute = new Timer();
execute.Interval = timeLeftUntilFirstRun.TotalMilliseconds;
execute.Elapsed += ElapsedEventHandler(doStuff);    // Event to do your tasks.
execute.Start();
Run Code Online (Sandbox Code Playgroud)

C.设置方法执行您要执行的操作。

 public void doStuff(object sender, ElapsedEventArgs e)
 { 
        // Do your stuff and recalculate the timer interval and reset the Timer.
 }
Run Code Online (Sandbox Code Playgroud)