Search code examples
batch-fileserverrestart

Automatically make a selection after 20 seconds


I made a custom start script for my Minecraft server so i could use more RAM. When you stop the server, it asks if you want to restart or if you want to stop. I can't get it to restart it automatically if you don't answer after 20sec (in case of a crash). Please help.

@echo off
title minecraft-server-1.8.3
color 0A
prompt [server]:
cls

:start                                          //starts the server
echo loading server...
java -Xms3G -Xmx3G -jar minecraft_server.1.8.3.jar nogui 
cls

[code to restart the server when it didn't get an anwser in 20sec]

:choice                                         //what to do when 
set /P a=do you want to restart[Y/N]?             the server stops
if /I "%a%" EQU "Y" goto :restart
if /I "%a%" EQU "N" goto :stop
goto :choice


:restart                                               
cls
echo server will restart
TIMEOUT /T 5
cls
goto :start

:stop

cls
echo closing server
TIMEOUT /T 5
exit

Solution

  • Instead of set /p use choice:

    choice /c YN /t 20 /d Y /m "Do you want to restart "
    
    • /c YN states the answer set (Y or N, case insensitive by the way).
    • /t 20 states a timeout of 20 seconds.
    • /d Y states the default answer Y once the timeout expires.
    • /m "..." states a prompt.

    choice sets errorlevel to the index of the input (Y:1, N:2) so to check the user input use:

    if %errorlevel% equ 1 goto :restart
    if %errorlevel% equ 2 goto :stop
    

    You can find more information about choice at http://ss64.com/nt/choice.html or type choice/?