Using Background Jobs

by Sep 25, 2015

Background jobs can help speed up your scripts. If your scripts consist of a number of separate tasks that also could run in parallel, then background jobs could be a good idea.

Background jobs are efficient if (a) the task takes at least 3-4 seconds and (b) the task does not return excessive amounts of data.

Here is a basic background job scenario consisting of 3 tasks. They would roughly take 23 seconds if run consecutively. With background jobs, they only take 11 seconds (the time of the longest single task) plus some overhead time.

#requires -Version 2 

# three things you want to do in parallel
# for illustration, Start-Sleep is used
# remove Start-Sleep and replace with real-world
# tasks
$task1 = { 
    Start-Sleep -Seconds 4 
    dir $home
$task2 = { 
    Start-Sleep -Seconds 8 
$task3 = { 
    Start-Sleep -Seconds 11
    'Hello Dude'

$job1 = Start-Job -ScriptBlock $task1
$job2 = Start-Job -ScriptBlock $task2

$result3 = & $task3

Wait-Job -Job $job1, $job2

$result1 = Receive-Job -Job $job1
$result2 = Receive-Job -Job $job2

Remove-Job $job1, $job2

Twitter This Tip! ReTweet this Tip!