每次完成时在Windows上重新启动程序

时间:2016-08-03 09:08:01

标签: java windows powershell

我已经用Java编写了一个索引程序,我需要尽可能多地运行#34;在Windows机器上,即

  1. 程序完成后,应重新启动。
  2. 当程序运行超过一小时时,应该终止并重新启动。
  3. 我考虑过编写一个永远运行的Java程序"但偶尔JVM会崩溃,因此这种方法似乎不可靠。

    我想我必须编写批处理文件或Powershell脚本,但实际上并不知道从哪里开始。

1 个答案:

答案 0 :(得分:0)

您可以尝试使用计时器对象,如下所示:

$filepath = 'C:\Windows\System32\calc.exe' #change this to your exe location
$exe = 'calc' #change this to your exe process name

$Timer = New-Object System.Timers.Timer
$Timer.Interval = 1000 #interval in ms
$Timer.Enabled = $true
$Action = {
    $process = Get-Process $exe
     if ($process)
     {
        if ((New-TimeSpan -Start $process.StartTime -End (Get-Date)) -gt ([timespan]'00.01:00:00')) #this timespan equals to 1 hour
        {
            Get-Process $exe | Stop-Process -Force
        }
     }
     else
     {
        Start-Process -FilePath $filepath
     }
     $process = $null
}
[void](Register-ObjectEvent -InputObject $Timer -EventName elapsed –SourceIdentifier Timer123456 -Action $Action)
$Timer.Start() #to start timer
#$Timer.Stop() #to stop timer

然后您可以在后台运行它,它将查看您想要的进程。

虽然您需要确保它具有唯一的进程名称。