让一个进程以定时间隔运行另一个进程

时间:2011-10-06 15:34:16

标签: c#

和我呆在一起一分钟:

进程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,并挂钩它,以便我可以检查它是否正在运行?

4 个答案:

答案 0 :(得分:2)

windows task scheduler已经完成了所有这些

答案 1 :(得分:2)

使用GetProcessesByName:

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

如果在本地ByName中获取任何内容,则该过程仍在运行。

MSDN Documentation.

答案 2 :(得分:0)

查看Process课程。

使用此类,您可以检索有关系统中进程的所有类型的信息。如果您自己启动该过程,则不必扫描所有进程,因此可以防止缓慢且容易出错的呼叫。

如果有Process对象,可以使用WaitForExit等待它完成。

你能做的是:

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

    }

答案 3 :(得分: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;
                    }
                }
            }
        }
    }