I need to make a batch file that calls a URL (without opening a browser), but only after 20 seconds since previous run. If it's run sooner than 20 seconds, the script does nothing and closes. How would I go about doing this?
2 Answers
If your batchfile waits 20 seconds before closing, and you can only have one instance of it running at a time, then the problem is solved.
Use a technique like this or this to make your batch file exit ,without doing anything else, if it is already running.
Then, if the batchfile does not detect another instance running, Use the timeout command at the end of the batchfile to wait 20 seconds.
timeout /t 20
@montewhizdoh: if you add a timeout at the end of the batch file, it means you have to wait for 20 seconds before the batch actually returns, which may not be desirable, especially if the operations it performs are supposed to occur quickly.
@seventy70: by recording the current time in a separate file, you can ensure that the batch will exit without doing anything you don't want it to, unless a certain number of seconds has elapsed. The following code achieves this:
@echo off
Setlocal EnableDelayedExpansion
set lastTime=86500
if NOT EXIST lasttime.txt goto :nextStep
for /f "delims=;" %%i in (lasttime.txt) do (
set lastTime=%%i
)
set /A lastTime=(%lastTime:~0,2%*3600) + (%lastTime:~3,2%*60) + (%lastTime:~6,2%)
:nextStep
set currTime=%TIME%
set /A currTime=(%currTime:~0,2%*3600) + (%currTime:~3,2%*60) + (%currTime:~6,2%)
:: required check in case we run the batch file right before and right after midnight
if %currTime% LSS %lastTime% (
set /A spanTime=%lastTime%-%currTime%
) else (
set /A spanTime=%currTime%-%lastTime%
)
if %spanTime% LSS 20 (
echo Only %spantime% have passed since the last run
goto :eof
)
:: ************************************
:: DO ACTUAL STUFF HERE
:: ************************************
if exist lasttime.txt del lasttime.txt
echo %time%>>lasttime.txt
endlocal
So every time the batch is allowed to run, it records the current time in a file. The next time around, it reads the file, extracts the time from it and compares it with the current time. If less than 20 seconds have elapsed, the batch exits. If more than 20 seconds have passed, the actual operations can be executed and at the end, the current time is recorded again in the control file for use next time around.

- 520
- 4
- 12