How to Set Command Timeout in Batch

Dr. Muhammad Abdullah Feb 02, 2024
  1. the timeout Command in Batch Script
  2. Set timeout for Any Other Command or Process
How to Set Command Timeout in Batch

This article will first discuss the concept of the timeout command in the Batch script. After this, we will discuss setting the timeout command for any other command.

the timeout Command in Batch Script

timeout is a utility to pause or delay for a specific period. This command makes a certain amount of break and creates a pause on the command-line interface.

The syntax of the timeout command is as follows:

timeout /t <time in seconds> [/nobreak]

The command timeout with /t is used to create a delay followed by <time in seconds>, an integer number from -1 to 100000, representing the amount of time in seconds for creating the delay, and an optional parameter /nobreak.

If we use -1 with the timeout command, it will create a delay for an indefinite period until any key is pressed.

Consider the following timeout command:

timeout /t 5

The timeout /t 5 command delays 5 seconds or until any key is not pressed. The output of the command is as follows:

Batch Timeout - Output 1

The optional parameter /nobreak is used to ignore any keystroke during the delay created by the timeout command. For example, consider the following command:

timeout /t 5 /nobreak

The output of the following command is as follows:

Batch Timeout - Output 2

We can hide the timeout command message, also. The command timeout /t 5 > nul is used to hide the message of the timeout command by redirecting the output message to nul.

Set timeout for Any Other Command or Process

We can delay a timeout for any other custom command or process. Consider the following Batch script:

@echo off
start  notepad.exe
timeout /t 4
taskkill /f /im  notepad.exe > nul && (
   echo Task is killed.
   exit /b 31744
) || (
   echo No Command or Task to kill. The task is terminated in time.
)

In the above Batch script, we use the @echo off command to hide the executing commands from the command prompt. The start notepad.exe command is used to start a process and launch the Notepad editor window.

The command timeout /t 4 command delays 4 seconds, followed by a taskkill command, which kills the notepad.exe process if it is not yet.

Further, this script shows the Task is killed. on the terminal if the taskkill command kills the notepad.exe process.

If the notepad.exe is already killed during the timeout delay, the taskkill command will not kill the notepad.exe and display the error message along with the following output:

No Command or Task to kill. The task is terminated in time.