如何在控制台应用程序中使用计时器?
如何在控制台应用程序中使用计时器? 例如,我希望我的控制台应用程序在后台运行并每 10 分钟执行一次操作。
我怎样才能做到这一点?
谢谢
How can I use a timer in my console application? I want my console application to work in the background and to do something every 10 minutes, for example.
How can I do this?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
控制台应用程序不一定要长时间运行。 话虽这么说,你可以做到。 为了确保控制台不只是退出,您必须让控制台在 Console.ReadLine 上循环以等待某些退出字符串,例如“quit”。
要每 10 分钟执行一次代码,请调用 System.Threading.Timer 并将其指向您的执行方法,间隔为 10 分钟。
编辑
不过,我喜欢日本央行对你的问题的评论。 如果您确实需要一个长时间运行的应用程序,请考虑将其设为 Windows 服务的开销。 虽然存在一些开发开销,但您可以获得更稳定的平台来运行代码。
Console applications aren't necessarily meant to be long-running. That being said, you can do it. To ensure that the console doesn't just exit, you have to have the console loop on Console.ReadLine to wait for some exit string like "quit."
To execute your code every 10 minutes, call System.Threading.Timer and point it to your execution method with a 10 minute interval.
EDIT
I like Boj's comment to your question, though. If you really need a long-running application, consider the overhead of making it a Windows Service. There's some development overhead, but you get a much more stable platform on which to run your code.
您只需使用 Windows 任务计划程序每 10 分钟运行一次控制台应用程序即可。
You can just use the Windows Task Scheduler to run your console application every 10 minutes.