2013-07-02 115 views
3

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

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

如果应用程序中没有输出,则应考虑创建服务。 –

+0

如果应用程序中没有输出,为什么写了'Console.Write'? –

+0

这是相同的问题http://stackoverflow.com/questions/2686289/how-to-run-a-net-console-app-in-the-background –

回答

7

为什么不只是使用Windows Task Scheduler

将其设置为以期望的时间间隔运行您的应用程序。这对于这类工作来说非常完美,你不必为强迫线程入睡而烦恼,这可能会产生更多的问题。

+0

这是一个免费服务 – user2543131

5

这个程序应该连续运行运行的代码,即把一条消息每隔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 
     } 

    } 
} 
+2

@Cemafor他编辑答案抗议WAS合法 – VeNoMiS

+1

@Cemafor他编辑了我的评论后的答案。不管间隔时间,他的初始代码都会运行。我已经删除它,因为它已不再相关 – DGibbs

+1

为什么你需要一段时间 – user2543131

1

也许最简单的方法是每隔X分钟“触发”一个新过程就是使用Windows Task Scheduler

你当然可以用编程方式做类似的事情,例如,创建您自己的服务,每隔X分钟启动一次控制台应用程序。


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

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 
    } 

} 
+0

你只需要防止在这里关闭控制台应用程序。 –

+0

在最后放置了一个'Console.ReadLine()',它将继续运行。 –

相关问题