PS Gotcha: Scheduled Jobs and Battery
April 20th, 2012 by KarlThe other day I was working with a ne wPSV3 feature called Scheduled Jobs which is really cool as it allows you run some stuff as a Scheduled job, which uses the Scheduled Task engine to run it. You can set triggers like on start up, but unfortunately, and this is something I am frustrated about, not “immediately”. However you can trigger it to say run in 5 seconds which is long enough to ensure even a slow computer is going to get to it before the time expires and it would never .
So often I’ll do a demo like
Register-ScheduledJob -name quicktest -ScriptBlock { 1; sleep 5; 2} -Trigger (New-JobTrigger -Once -At (get-date).AddSeconds(4))
sleep 6
get-job quicktest | wait-job | Receive-Job
What this does is register a scheduled Job, which triggers in a few seconds, sleep to make sure it gets triggered, then uses get-job , which gets the job INSTANCE of the scheduled job, and does the normal stuff to wait and receive the data.
This works all good and dandy. Other than when it doesn’t, which according to the laws of DEMO, happens in a demo. So I ran something like this, and the job never seemed to be triggered. I tried again and again and I just couldn’t get it to work. and from the PowerShell side of things there just was no indication of error. it is as if I had never tried to run it.
So I started poking around in Task Scheduler. PowerShell stores the Scheduled tasks at \Microsoft\Windows\PowerShell\ScheduledJobs
Aha found the culprit. I was taking my laptop somewhere else to do the demo and had plenty of battery, However by default (not a bad thing) scheduled Tasks won’t launch when on battery.
It is a shaming pity that PSV3 doesn’t capture the error and create and failed job instance with the error. that would be definitely useful, and consistent with the PowerShell Job experience in general. At least we should have a Cmdlet that can show us warnings and errors for our scheduled jobs.
There are many reasons why a scheduled task can’t launch , from permissions, to this battery thing, to concurrency issues (i.e by default the policy only allows once instance of a scheduled task to run at once)
In my sample I could have just updated the policy to allow it to run on battery (-ScheduledJobOption (New-ScheduledJobOption -StartIfOnBattery), but still the point is it failed, and there was no indication of why. So be aware of these situations and work around them.
Register-ScheduledJob -name quicktest -ScriptBlock { 1; sleep 5; 2} `
-Trigger (New-JobTrigger -Once -At (get-date).AddSeconds(4)) `
-ScheduledJobOption (New-ScheduledJobOption -StartIfOnBattery)
sleep 6
get-job quicktest | wait-job | Receive-Job
Posted in Gotchas Etc, Powershell, PSV3 | No Comments »
