简体   繁体   中英

how to continuously run a c# console application in background

I would like to know how to run ac# program in background every five minute increments. The code below is not what I would like to run as a background process but would like to find out the best possible method to do this using this code so that I can implement it on another code. so this process should run after a five minute increment. I know I could use threads to do so, but dont really now how to implement this. I know this is the best way How to run a console application on system Startup , without appearing it on display(background process)? this to run in the background, but how would I have the code running in five minute increments

 class Program
    {
        static void Main(string[] args)
        {
            Console.Write("hellow world");
            Console.ReadLine();
        }
    }

This app should run continuously, putting out a message every 5 minutes.
Isn't that what you want?

class Program
{
    static void Main(string[] args)
    {
        while (true) {
            Console.Write("hellow world");
            System.Threading.Thread.Sleep(1000 * 60 * 5); // Sleep for 5 minutes
        }

    }
}

Why not just use Windows Task Scheduler ?

Set it to run your app at the desired interval. It's perfect for this sort of job and you don't have to mess about with forcing threads to sleep which can create more problems that it solves.

How about using a System.Windows.Threading.DispatcherTimer ?

class Program
{
    static void Main(string[] args)
    {
        DispatcherTimer timer = new DispatcherTimer();
        timer.Interval = new TimeSpan(0, 5, 0); // sets it to 5 minutes
        timer.Tick += new EventHandler(timer_Tick);
        timer.Start();
    }

    static void timer_Tick(object sender, EventArgs e)
    {
        // whatever you want to happen every 5 minutes
    }

}

Probably the simplest way to "fire" a new process every X minutes is to use Windows Task Scheduler .

You could of course do something similar programmatically, eg create your own service, that starts the console application every X minutes.


All this under assumption you actually want to close the application before the next iteration. Alternatively, you might just keep it active the whole time. You might use one of the timer classes to fire events periodically, or even a Thread.Sleep in a very simplified scenario....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM