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.
如何在我的控制台应用程序中使用计时器?我希望我的控制台应用程序在后台工作,并且每隔10分钟做一次事情。
How can I do this?
我怎样才能做到这一点?
Thanks
2 个解决方案
#1
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."
控制台应用程序不一定意味着长时间运行。话虽这么说,你可以做到。要确保控制台不仅仅退出,您必须在Console.ReadLine上安装控制台循环以等待某些退出字符串,如“退出”。
To execute your code every 10 minutes, call System.Threading.Timer and point it to your execution method with a 10 minute interval.
要每10分钟执行一次代码,请调用System.Threading.Timer并将其指向执行方法,间隔为10分钟。
public static void Main(string[] args)
{
using (new Timer(methodThatExecutesEveryTenMinutes, null, TimeSpan.FromMinutes(10), TimeSpan.FromMinutes(10)))
{
while (true)
{
if (Console.ReadLine() == "quit")
{
break;
}
}
}
}
private static void methodThatExecutesEveryTenMinutes(object state)
{
// some code that runs every ten minutes
}
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.
不过,我喜欢Boj对你问题的评论。如果您确实需要长时间运行的应用程序,请考虑将其作为Windows服务的开销。有一些开发开销,但您可以获得一个更稳定的平台来运行您的代码。
#2
You can just use the Windows Task Scheduler to run your console application every 10 minutes.
您可以使用Windows任务计划程序每10分钟运行一次控制台应用程序。
#1
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."
控制台应用程序不一定意味着长时间运行。话虽这么说,你可以做到。要确保控制台不仅仅退出,您必须在Console.ReadLine上安装控制台循环以等待某些退出字符串,如“退出”。
To execute your code every 10 minutes, call System.Threading.Timer and point it to your execution method with a 10 minute interval.
要每10分钟执行一次代码,请调用System.Threading.Timer并将其指向执行方法,间隔为10分钟。
public static void Main(string[] args)
{
using (new Timer(methodThatExecutesEveryTenMinutes, null, TimeSpan.FromMinutes(10), TimeSpan.FromMinutes(10)))
{
while (true)
{
if (Console.ReadLine() == "quit")
{
break;
}
}
}
}
private static void methodThatExecutesEveryTenMinutes(object state)
{
// some code that runs every ten minutes
}
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.
不过,我喜欢Boj对你问题的评论。如果您确实需要长时间运行的应用程序,请考虑将其作为Windows服务的开销。有一些开发开销,但您可以获得一个更稳定的平台来运行您的代码。
#2
You can just use the Windows Task Scheduler to run your console application every 10 minutes.
您可以使用Windows任务计划程序每10分钟运行一次控制台应用程序。