powershell - 启动工作后不必要的延迟

时间:2014-01-08 21:02:48

标签: powershell

请考虑以下powershell脚本:

$script = {
    Write-Host "Start job: $(Get-Date)"
    1..3 | ForEach-Object {
        Write-Host "Job count: $_ $(Get-Date)"
        Start-Sleep 1
    }
    Write-Host "Stop job: $(Get-Date)"
}

Write-Host "Start script:  $(Get-Date)"
$job = Start-Job $script
1..10 | ForEach-Object {
    Write-Host "Waiting: $_ $(Get-Date)"
    Receive-Job $job
    Start-Sleep 1
}
Write-Host "Stop script:  $(Get-Date)"

它的输出:

Start script:  01/08/2014 21:57:44
Waiting: 1 01/08/2014 21:57:44
Waiting: 2 01/08/2014 21:57:45
Waiting: 3 01/08/2014 21:57:46
Waiting: 4 01/08/2014 21:57:47
Start job: 01/08/2014 21:57:46
Job count: 1 01/08/2014 21:57:46
Waiting: 5 01/08/2014 21:57:48
Job count: 2 01/08/2014 21:57:47
Waiting: 6 01/08/2014 21:57:49
Job count: 3 01/08/2014 21:57:48
Waiting: 7 01/08/2014 21:57:50
Stop job: 01/08/2014 21:57:49
Waiting: 8 01/08/2014 21:57:51
Waiting: 9 01/08/2014 21:57:52
Waiting: 10 01/08/2014 21:57:53

为什么启动脚本和启动作业之间有2秒的延迟?以及如何预防?

1 个答案:

答案 0 :(得分:0)

作业在主脚本的单独Powershell会话中运行。创建和初始化该会话需要一些时间。后台作业适用于长时间运行的任务。如果在您的应用程序中创建会话所花费的几秒钟时间很长,那么它可能不适合作为后台作业运行。