Linux repeat command every 5 seconds

How to Run or Repeat a Linux Command Every X Seconds Forever

A system administrator often needs to run a command repeatedly in a certain periods of time. Often such tasks can be easily completed with simple cron commands. In most of the cases this should work, but the shortest period which you can run cron command is every 1 minute. Believe it or not, in many cases this is too slow.

Run Linux Command Every Second

In this tutorial, you will learn a simple scripting techniques to monitor or keep a eye on a particular command in continuously running state similar to top command (continuously monitor the process and memory utilization) for every 3 seconds by default.

We will not stop to discuss the reasons, why you would need to run commands this often. I believe everyone has different reasons for that in their daily jobs or even at home PCs and laptops.

1. Use watch Command

Watch is a Linux command that allows you to execute a command or program periodically and also shows you output on the screen. This means that you will be able to see the program output in time. By default watch re-runs the command/program every 2 seconds. The interval can be easily changed to meet your requirements.

Monitor Memory Usage

“Watch” is extremely easy to use, to test it, you can fire up a Linux terminal right away and type the following command:

The above command will check your system free memory and update the results of the free command every two seconds.

Monitor Memory Usage in Linux

As seen per the above output, you have a header, displaying information about (from left to right) update interval, command that is being executed and current time. If you wish to hide this header, you can use the -t option.

The next logical question is – how to change the execution interval. For that purpose, you can use the -n option, that specifies the interval with which the command will be executed. This interval is specified in seconds. So let’s say you want to run your script.sh file every 10 seconds, you can do it like this:

Note that if you run the command like shown above, you will need to cd to the directory (learn Learn 15 cd Command Examples) where the script is located or otherwise specify the full path to that script.

Other useful options of watch command are:

  1. -b – creates a beep sound if the exit of the command is non-zero.
  2. -c – Interprets ANSI color sequences.
  3. -d – highlights the changes in the command output.

Monitor Logged-In Users, Uptime and Load Average

Let’s say you want to monitor logged-in users, server uptime and load average output in continuously phase every few seconds, then use following command as shown:

Watch Linux Load Average

To exit the command, press CTRL+C .

Here, the ‘uptime’ command will run and display the updated results every 2 seconds by default.

Monitor Progress of Copy Command

In Linux, while copying files from one location to other using cp command, the progress of data is not shown, to see the progress of data being copied, you can use the watch command along with du -s command to check the disk usage in real time.

Monitor Progress of Copy Command

If you think that the above process is too complicated to achieve, then I suggest you to go for Advance copy command, which shows progress of data while copying.

Читайте также:  Сам запускается windows media player

2. Use sleep Command

Sleep is often used to debug shell scripts, but it has many other useful purposes as well. For example, when combined with for or while loops, you can get pretty awesome results.

If you are new to bash scripting, you can check our guide about bash loops here.

In case this is the first time you hear about the «sleep» command, it is used to delay something for a specified amount of time. In scripts, you can use it to tell your script to run command 1, wait for 10 seconds and then run command 2.

With the above loops, you can tell bash to run a command, sleep for N amount of seconds and then run the command again.

Below you can see examples of both loops:

for loop Example

The above one liner, will run the echo command and display the current date, total of 10 times, with 5 seconds sleep between executions.

Here is a sample output:

You can change the echo and date commands with your own commands or script and change the sleep interval per your needs.

while loop Example

Here is sample output:

The above command will run until it is either killed or interrupted by the user. It can come in handy if you need to run a command running in the background and you don’t want to count on cron.

Important: When using the above methods, it is highly recommend that you set interval long enough to give enough time of your command to finish running, before the next execution.

Conclusion

The samples in this tutorial are useful, but are not meant to completely replace the cron utility. It is up to you to find which one works better for you, but if we have to separate the usage of both techniques, I would say this:

  1. Use cron when you need to run commands periodically even after system reboots.
  2. Use the methods explained in this tutorial for programs/scripts that are meant to run within the current user session.

As always if you have any questions or comments, do not hesitate to submit them in the comment section below.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Источник

How To Repeat A Command Every X Seconds On Linux

This article explains how to repeat a command every X seconds on Linux, in 2 ways: using watch , and using sleep in a while loop (with a way to avoid time drift when using long-running commands).

Using watch to run a command every X seconds

watch can run a command repeatedly, displaying its output and errors (the first screenful). This allows you to watch the program output change over time.

Using watch to run a command every X seconds:

  • -n specifies the time interval
  • X is the interval at which to run the command, in seconds (with 0.1 seconds being the lowest possible value)
  • command is the command you want to run

If the command contains pipes, quotes or other special characters, use single quotes, e.g.: ‘command’ .

Example. The following command runs ps aux | grep firefox every 5 seconds:

The watch command has a few options, like highlighting the differences between successive updates ( —differences / -d ), beep if a command has a non-zero exit ( —beep / -b ), and more. Check out its man page for more information.

Using sleep in a while loop to repeat a command every X seconds

Another way of repeating a command every X seconds on Linux is to use a while loop with the sleep command:

Here, you need to replace command with the command to run, and X with the time interval in seconds (the number doesn’t have to be an integer, but it can’t be negative; you can also specify minutes — 1m for example, hours — 1h for example, etc.).

Читайте также:  Не работает сетевой адаптер windows 10 64 bit

Example. The following one-liner runs the echo $(date) command every 5 seconds:

If you’re doing something more complicated, make sure that the interval is shorter than the time required for the command to finish, or else this might interfere with something in your script.

It’s also important to note that using this, time will drift, depending on how long the command you’re running takes to complete. For example, if you want to run a command every 5 seconds, but that command takes 3 seconds to complete, this will cause the command to run every 8 seconds, instead of every 5 seconds.

A solution for avoiding this time drift, and running the command every X seconds regardless of how long it takes to complete (as long as the command doesn’t take more to complete than the sleep time), is to use the following:

Here, replace command with the command you want to run, and both instances of X with the number of seconds after which the command should be repeated.

[[Edit]] This solution is not perfect. Read the explanation and alternative to this in the marked edits further down this article.

Example. The following one-liner repeats the sleep 3 command (I couldn’t think of a better example right now of a command that takes a few seconds to complete and isn’t destructive in any way in case the user doesn’t stop it — I’m typing this at 5 AM) every 5 seconds:

Using this, even though the command ( sleep 3 in this case, it can be any command you want) takes 3 seconds to complete, the interval between runs is 5 seconds.

For testing this you can add an echo $(date) at the beginning, like this:

You’ll notice that the date printed in the terminal is in increments of 5 seconds, like this:

[[Edit]] This solution is not perfect though. Between the first and second run, the time interval may be shorter than the one you’ve specified. Subsequent runs use the correct time interval though. If you know a better way to do this, please leave a comment below.

[[Edit]] A solution (via stackexchange) which avoids time drifting, and doesn’t have the issue I mentioned above (so no different time interval between the first and second run), but which doesn’t make use of the sleep command, is the following one-liner:

Replace X with the time interval between runs (in seconds), and command with the command you want to repeat every X seconds.

A bit of an explanation is in order here. This while loop stores the current Unix time as currentTime , then it subtracts the last time ( lastTime ) from the current time, storing it as elapsedTime . Next it checks if the elapsed time is greater or equal to X and if it is, it runs command (so the command is repeated every X seconds). And finally, it sets the last time to be equal to the current time, so the next time it runs it can subtract lastTime from the currentTime , which gives the elapsedTime value. I hope this makes sense to you as it does in my head 😁️.

Example. The following one-liner repeats the echo $(date) and sleep 2 commands (I used sleep 2 so the command takes a couple of seconds to complete, to be able to check if time is drifting or not) every 5 seconds:

Источник

How to run or repeat a Linux command every X seconds forever

A Linux system administrator needs to know some Linux tricks. In this article, you will learn How to run or repeat a Linux command every X seconds forever.

You may need to run a command repeatedly in a certain period of time. Using simple cron commands, such tasks can be easily completed.

Follow this guide to learn simple scripting techniques to monitor or keep an eye on a particular command in continuously running state similar to top command for every 3 seconds by default.

Table of Contents

How to run or repeat a Linux command every X seconds forever

Let’s do not give up and start discussing the reasons of why you would need to run commands this often and reach to the answer of How to run or repeat a Linux command every X seconds forever.

Use watch Command

In order to use Watch command, you will be able to execute a command or program periodically and also shows your output on the screen. So you can see the program output in time. The interval can be easily changed to meet your requirements, and also watch re-runs the command/program every 2 seconds. The interval can be easily changed.

Читайте также:  Как удаленно администрировать windows

Monitor Memory Usage

Since using “Watch” is extremely easy, you can test it by firing up a Linux terminal right away and type the following command:

After using the above command, your system free memory will be checked and the result of the free command will be updated every two seconds.

In case you need to hide the header, displaying information about update interval, command that is being executed, and the current time, use the -t option.

Then, use the -n option to change the execution interval to let it specify the interval with which the command will be executed. Soto run your script.sh file every 10 seconds, you can do it like this:

Therefore, after running the above command, you will need to cd to the directory where the script is located or otherwise specify the full path to that script.

Have a look at the following options to see other watch command useful options.

  1. -b – creates a beep sound if the exit of the command is non-zero.
  2. -c – Interprets ANSI color sequences.
  3. -d – highlights the changes in the command output.

Monitor Logged-In Users, Uptime and Load Average

To continue this step, use the following command.

Press CTRL+C to exit the command.

Here, the ‘ uptime ‘ command will run and display the updated results every 2 seconds by default.

Monitor Progress of Copy Command

As you guess, in Linux while copying files from one location to others using cp command, the progress of data is not shown. Use the watch command, to see the progress of data being copied.

Use sleep Command

Sleep is used in many useful situations, Two of the are often for debugging shell scripts and when combined with for or while loops, you can get pretty awesome results.

But do not worry if this is the first time you hear about the “ sleep ” command, it is used to delay something for a specified amount of time. In scripts, you can use it to tell your script to run command 1, wait for 10 seconds, and then run command 2.

Having the above loops, you can tell bash to run a command, sleep for N amount of seconds and then run the command again.

Let’s see examples of both loop:

for loop Example

The above one-liner, will run the echo command and display the current date, a total of 10 times, with 5 seconds sleep between executions.

Also, please consider that you are able to change the echo and date commands with your own commands or script and change the sleep interval per your needs.

while loop Example

Until it is either killed or interrupted by the user, the above command will run. It is so useful in case you want to run a command running in the background and you don’t want to count on corn.

Please Note : When using the above methods, it is highly recommended that you set an interval long enough to give enough time of your command to finish running, before the next execution.

Please Consider : The samples in this tutorial are useful but are not meant to completely replace the cron utility. It is up to you to find which one works better for you, but if we have to separate the usage of both techniques, I would say this:

  • Use cron when you need to run commands periodically even after system reboots.
  • Use the methods explained in this tutorial for programs/scripts that are meant to run within the current user session.

Dear user, we wish this tutorial How to run or repeat a Linux command every X seconds forever would be helpful for you, to ask any question or review the conversation of our users about this article, please visit Ask page . Also to improve your knowledge, there are so many useful tutorials ready for Eldernode training .

Do not miss some related articles:

Источник

Оцените статью