如何在后台连续运行c#console应用程序

时间:2013-07-02 14:56:26

标签: c#

我想知道如何以每五分钟为增量在后台运行一个c#程序。下面的代码不是我想作为后台进程运行的,而是想找到使用此代码执行此操作的最佳方法,以便我可以在另一个代码上实现它。所以这个过程应该在五分钟后增加。我知道我可以使用线程这样做,但现在不知道如何实现这一点。我知道这是在后台运行的最佳方式How to run a console application on system Startup , without appearing it on display(background process)?,但我如何以五分钟的增量运行代码

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

4 个答案:

答案 0 :(得分:7)

这个应用应该持续运行,每5分钟发一条消息 这不是你想要的吗?

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

    }
}

答案 1 :(得分:7)

为什么不使用Windows Task Scheduler

将其设置为以所需的时间间隔运行您的应用。它非常适合这类工作,你不必为强迫线程睡眠而烦恼,这可能会产生更多的问题。

答案 2 :(得分:1)

可能每隔X分钟“触发”一个新进程的最简单方法是使用Windows Task Scheduler

您当然可以通过编程方式执行类似操作,例如:创建自己的服务,每隔X分钟启动一次控制台应用程序。


所有这些假设您实际上想要在下一次迭代之前关闭应用程序。或者,您可以一直保持活动状态。您可以使用one of the timer classes定期触发事件,甚至可以在非常简化的场景中使用Thread.Sleep ....

答案 3 :(得分:1)

如何使用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
    }

}
相关问题