How do I schedule a task at a random time via batch file?
Try this:
@echo off
setlocal enabledelayedexpansion
call :rand 1 1 dummy
call :rand 11 21 ret
call :rand 0 59 ret2
if %ret2% LSS 10 set ret2=0%ret2%
echo schtasks /create /tn "task" /tr c:\task.vbs /d SUN /sd 10/28/2012 /st %ret%:%ret2%:00 /ru "" > task.txt 2>&1
exit /b
:rand
setlocal
SET /A RAND_NUM=%RANDOM% * (%2 - %1 + 1) / 32768 + %1
endlocal & set %~3=%RAND_NUM%
exit /b
Output:
schtasks /create /tn "task" /tr c:\task.vbs /d SUN /sd 10/28/2012 /st 11:00:00 /ru ""
U:\Scripts\Batch>RandomNumBetween.cmd
schtasks /create /tn "task" /tr c:\task.vbs /d SUN /sd 10/28/2012 /st 16:7:00 /ru ""
U:\Scripts\Batch>RandomNumBetween.cmd
schtasks /create /tn "task" /tr c:\task.vbs /d SUN /sd 10/28/2012 /st 17:46:00 /ru ""
U:\Scripts\Batch>RandomNumBetween.cmd
schtasks /create /tn "task" /tr c:\task.vbs /d SUN /sd 10/28/2012 /st 19:35:00 /ru ""
U:\Scripts\Batch>RandomNumBetween.cmd
schtasks /create /tn "task" /tr c:\task.vbs /d SUN /sd 10/28/2012 /st 13:54:00 /ru ""
U:\Scripts\Batch>RandomNumBetween.cmd
schtasks /create /tn "task" /tr c:\task.vbs /d SUN /sd 10/28/2012 /st 14:51:00 /ru ""
U:\Scripts\Batch>RandomNumBetween.cmd
schtasks /create /tn "task" /tr c:\task.vbs /d SUN /sd 10/28/2012 /st 21:48:00 /ru ""
If you schedule the task with schtasks
and want the start time to vary every time the task is run, you can use this in a batch file:
:: Delay for up to 5 minutes (300 seconds)
set /A DELAY=%RANDOM% %% 301
ping /n %DELAY% /w 1000 localhost > NUL
You could use timeout
instead of ping
on Windows 7/Server 2008+.