2011-10-06 30 views
2

與我保持一分鐘:讓一個進程按時間間隔運行另一個進程

進程A是我的主要工作進程。運行時,它處理信息。可能需要30秒到20分鐘才能完成。這個過程有多種變化,並不完全穩定。如果它崩潰了,這並不是什麼大不了的事情,因爲它可以在下次運行時停止。

過程B是我的首發過程。我希望它按給定的時間間隔運行進程A(如每5分鐘一次)。如果進程A已經在運行,那麼進程B應該等到下一個時間間隔才能嘗試。 IE ...

if(!ProcessA.isRunning) 
    ProcessA.Run(); 
else 
    Wait Until Next Interval to try 

過程A或多或少被寫入。我認爲它將是它自己的.exe,而不是使用多線程來實現這一點。

我的問題是:如何編寫運行單獨的.exe的進程B,並將其掛接到它,以便檢查它是否正在運行?

回答

2

使用GetProcessByName的像這樣:

// Get all instances of Notepad running on the local 
// computer. 
Process [] localByName = Process.GetProcessesByName("notepad"); 

如果得到localByName任何東西,則進程仍在運行。

MSDN Documentation.

+0

只希望別人沒有一個名爲「記事本」的進程。 。 。 –

0

看看在Process類。

使用此類可以檢索有關係統中的進程的所有類型的信息。如果您自己啓動流程,則不必掃描所有流程,因此可以防止緩慢且容易出錯的呼叫。

當有一個Process對象時,可以使用WaitForExit等到它完成。

你可以做的是:

var startOtherProcess = true; 
    while (startOtherProcess) { 
     var watchedProcess = Process.Start("MyProgram.Exe"); 
     watchedProcess.WaitForExit(); 
     if (testIfProcessingFinished) { 
      startOtherProcess = false; 
     } 

    } 
0

這裏是下面的代碼是如何工作的: 它檢查是否指定的進程中運行,如果是它忽略,否則它運行你所需要的。間隔使用System.Timers.Timer

[DllImport("user32.dll")] 
    [return: MarshalAs(UnmanagedType.Bool)] 
    static extern bool SetForegroundWindow(IntPtr hWnd); 

    public void RunProcess() 
    { 
     bool createdNew = true; 
     using (Mutex mutex = new Mutex(true, "MyApplicationName", out createdNew)) 
     { 
      if (createdNew) 
      { 
       // Here you should start another process 
       // if it's an *.exe, use System.Diagnostics.Process.Start("myExePath.exe"); 
      } 
      else 
      { 
       Process current = Process.GetCurrentProcess(); 
       foreach (Process process in Process.GetProcessesByName(current.ProcessName)) 
       { 
        if (process.Id != current.Id) 
        { 
         SetForegroundWindow(process.MainWindowHandle); 
         break; 
        } 
       } 
      } 
     } 
    } 
相關問題