1

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

1
  • 4
    Just to note: it's very easy to kill a console application. If this background job is important then choose windows service implementation. Or consider nandos's post about WTS. Commented Apr 16, 2009 at 21:29

2 Answers 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.

Sign up to request clarification or add additional context in comments.

2 Comments

What doesn't work about it? I tested it before I posted it. Just put a Console.WriteLine in methodThatExecutesEveryTenMinutes and change FromMinutes(10) to FromSeconds(5) to verify. It will print to the console every five seconds.
@MichaelMeadows Your answer is what I am looking for, However Windows service does not give you output feedback, such as console.writeline so, if you keep console application open, you can check outputs from the program to make sure it is running fine. It is kind of self reporting.
2

You can just use the Windows Task Scheduler to run your console application every 10 minutes.

1 Comment

This is probably the best way to do this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.