How to prevent scheduled tasks from running as soon as computer wakes up?
Example: I have a task that is scheduled for 6 am every day (only if I'm logged on). If my computer sleeps/hibernates all night until 9am, upon waking up the task will then run even though it missed its 6am schedule. I don't want that to happen as it's important that the task runs only at 6am.
I thought that unchecking the "Run task as soon as possible after a scheduled start is missed" setting would prevent this, but it doesn't. Is there another setting I should try so that the task will run only if the computer is on at the scheduled time (and will wait until the next scheduled time if it misses it)?
An example of my settings:
I found a workaround: make your task launching your .bat
script, which will launch the command if it discovers computer wasn't asleep. Script I use is:
@echo off
for /f "delims=" %%t in ('time /t') do if "%%t"=="%1" %~2
This script takes two parameters: first is time when the command is intended to be called, and the second is command itself, in quotes, like script.bat 21:40 "echo x"
.
Explanation
Unlike in Bash, in Batch it's impossible to directly store command output in variable, but one can iterate over it's output line after line. That's what my second line does. Because time /t
's output
is single line, there is only one iteration, in which the script launches the command (passed as second parameter) if script was called when you wanted it to be called; this condition will not be meet when this is delayed execution of the script.
I use %~2
instead of %2
, because %~2
discards quotes around command,
so that passing "echo x"
will execute echo
with argument x
, printing x
,
instead of invoking program echo x
with no arguments.
Drawbacks
Launching task on demand will do nothing, you'd better uncheck field Allow task to be run on demand in the Settings tab, not to be confused by that,
Modifying task's execution hour requires modifying the arguments to keep the task working,
-
time /t
's output depends on the regional settings.