C#如何在特定时间触发事件? [英] C# How can I trigger an event at a specific time of day?
问题描述
我正在处理一个程序,需要在一天的某个小时删除一个文件夹(然后重新实例化),这个时间将由用户给出。
I'm working on a program that will need to delete a folder (and then re-instantiate it) at a certain hour of the day, and this hour will be given by the user.
小时很可能是在夜间,因为没有人正在访问该文件夹(在工作时间外)。有没有办法在那个特定的时间触发这个事件?
The hour will most likely be during the night, because that's when nobody is accessing the folder (it's outside working hours). Is there a way to trigger that event at that certain hour?
我知道计时器,但是有没有一个更简单的方法来做,没有一个计时器,勾选和检查看看是什么时间?
I know about timers, but is there an easier way to do this without a timer that ticks and checks to see what time it is?
编辑:也许我不够具体。我想触发一个方法来做某事,而不必首先在单独的可执行文件中编译它。此方法是作为Windows服务实现的较大类的一部分。所以这个服务不断运行,但是在一天的某个时间,它应该触发这个功能来删除文件夹。
EDIT: Maybe I wasn't specific enough. I want to trigger a method to do something, without having to first compile it in a separate executable. This method is part of a bigger class that is implemented as a Windows Service. So this service continuously runs, but at a certain time of day, it should trigger this function to delete the folder.
谢谢。
推荐答案
开箱即用。
不需要对这种工作进行编码 - 使用计划任务,他们已经在Windows中很长一段时间了。
No need for coding on this kind of job - use Scheduled Tasks, they have been in windows for a long time. You can kick off your program from this.
更新:(以下更新到问题)
Update: (following update to question)
如果您需要从已经运行的服务触发方法,请使用计时器并根据您的目标时间测试 DateTime.Now
。
If you need to trigger a method from an already running service, use a timer and test DateTime.Now
against your target time.
这篇关于C#如何在特定时间触发事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!