How to Run a Command with Time Limit (Timeout) In Linux


Sometimes a Unix command may run for a very long time without giving the final output or it make a processing giving partial output from time to time. In such scenario we will like to put a time frame within which either the command mast complete for the process should abort. This is achieved by using below options.

Using timeout Tool

The Timeout tool forces a command tour abort if it cannot complete within a given time frame. Below is the syntax and example.

Syntax

timeout DURATION COMMAND [ARG]...

Where Duration is the number seconds you want the command to run
Before aborting if the execution is not complete. In duration flag we have,
s - seconds
m - minutes
h - hours
d - days

Example

In the below example we use the ping command to ping our website and the process remains on only for 5 seconds after which the command stops running automatically.

$ timeout 5s ping tutorialspoint.com

Running the above code gives us the following result −

PING tutorialspoint.com (94.130.82.52) 56(84) bytes of data.
64 bytes from tutorialspoint.com (94.130.82.52): icmp_seq=1 ttl=128 time=126 ms
64 bytes from tutorialspoint.com (94.130.82.52): icmp_seq=2 ttl=128 time=126 ms
64 bytes from tutorialspoint.com (94.130.82.52): icmp_seq=3 ttl=128 time=126 ms
64 bytes from tutorialspoint.com (94.130.82.52): icmp_seq=4 ttl=128 time=126 ms
64 bytes from tutorialspoint.com (94.130.82.52): icmp_seq=5 ttl=128 time=127 ms

Using timelimit

The timelimit program needs to be installed, to get this feature for killing the command after a certain time. It will pass the warning signal and then after timeout, it will send the kill signal. You can also pass argumnets like - arguments like, killtime, warntime etc. So this command gives us a finer control to warn and kill the commands.

First we install the program using below command.

sudo apt-get install timelimit

Next we see the below example to use timelimit. Here –t specifies the maximum execution time of the process in seconds before sending warnsig and T is the maximum execution time of the process before sending killsig after warnsig has been sent.

timelimit -t6 -T12 ping tutorialspoint.com

Running the above code gives us the following result −

PING tutorialspoint.com (94.130.82.52) 56(84) bytes of data.
64 bytes from tutorialspoint.com (94.130.82.52): icmp_seq=1 ttl=128 time=127 ms
64 bytes from tutorialspoint.com (94.130.82.52): icmp_seq=2 ttl=128 time=126 ms
64 bytes from tutorialspoint.com (94.130.82.52): icmp_seq=3 ttl=128 time=126 ms
64 bytes from tutorialspoint.com (94.130.82.52): icmp_seq=4 ttl=128 time=127 ms
64 bytes from tutorialspoint.com (94.130.82.52): icmp_seq=5 ttl=128 time=128 ms
64 bytes from tutorialspoint.com (94.130.82.52): icmp_seq=6 ttl=128 time=126 ms
timelimit: sending warning signal 15

Updated on: 25-Feb-2020

455 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements