在linux上,有timeout
命令,它具有非常简单的语法:
timeout 120 command [args]
这很简单。它运行该命令,并在该命令超过时限时将其杀死。尽管我已尽力而为,但Windows上的“解决方案”是多行,不会显示命令输出到终端,如果我将超时时间增加到一分钟以上,cygwin的“timeout”将无法终止该进程(对此没有任何解释)。有谁有更好的主意吗?
最佳答案
我的意思是有 timeout.exe
,但我认为这不会为您提供与您所寻找的功能完全相同的功能。
我不知道Windows的timeout
等效项。按照linked answer PowerShell作业中的建议,将提出有关如何复制timeout
行为的建议。我滚动了一个简单的示例函数
function timeout{
param(
[int]$Seconds,
[scriptblock]$Scriptblock,
[string[]]$Arguments
)
# Get a time stamp of before we run the job
$now = Get-Date
# Execute the scriptblock as a job
$theJob = Start-Job -Name Timeout -ScriptBlock $Scriptblock -ArgumentList $Arguments
while($theJob.State -eq "Running"){
# Display any output gathered so far.
$theJob | Receive-Job
# Check if we have exceeded the timeout.
if(((Get-Date) - $now).TotalSeconds -gt $Seconds){
Write-Warning "Task has exceeded it allotted running time of $Seconds second(s)."
Remove-Job -Job $theJob -Force
}
}
# Job has completed natually
$theJob | Remove-Job -ErrorAction SilentlyContinue
}
这将启 Action 业并继续检查其输出。因此,您应该获得正在运行的进程的实时更新。您不必使用
-ScriptBlock
,而可以选择基于-Command
的作业。我将展示一个使用上述功能和脚本块的示例。timeout 5 {param($e,$o)1..10|ForEach-Object{if($_%2){"$_`: $e"}else{"$_`: $o"};sleep -Seconds 1}} "OdD","eVeN"
这将打印数字1到10以及数字均匀度。在显示数字之间,会有1秒钟的暂停。如果达到超时,将显示警告。在上面的示例中,由于仅允许该过程5秒钟,因此不会显示所有10个数字。
功能可能需要一些修饰,并且可能有人已经这样做了。至少我是这样。
关于windows - Windows的等效超时,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46374893/