2014-01-08 23 views
1

考慮以下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秒延時?以及如何預防?

回答

0

作業在主腳本的單獨Powershell會話中運行。創建和初始化該會話將需要一些時間。後臺作業適用於長時間運行的任務。如果在您的應用程序中創建會話需要幾秒鐘的時間,那麼它可能不適合作爲後臺作業運行。