1

如何在控制台应用程序中使用计时器?例如,我希望我的控制台应用程序在后台工作并每 10 分钟执行一次。

我怎样才能做到这一点?

谢谢

4

2 回答 2

4

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.

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.

于 2009-04-16T21:24:41.973 回答
2

您可以使用 Windows 任务计划程序每 10 分钟运行一次控制台应用程序。

于 2009-04-16T21:16:18.077 回答