commands.page Website Logo

  • Home
  • Categories
  • Search

How to Run a Command Every Set Period of Time on the Terminal in Ubuntu

This is an article about how to schedule commands to run at regular intervals using various tools available within the Linux environment, specifically targeting users working with Ubuntu. In this article you will find information on setting up cron jobs and utilizing shell scripts for automated task execution. Whether it’s monitoring system health, automating backups, or simply keeping track of log files over time, scheduling tasks can save a significant amount of time and effort.

In this guide, we’ll cover the basics of using cron, which is one of the most popular tools used to automate repetitive tasks in Linux systems like Ubuntu. We will also explore other methods such as watch command for more immediate needs or creating custom shell scripts with loops for simpler scenarios. Read this article to find out how you can make your life easier by automating routine terminal commands.

Understanding Cron Jobs

Cron is a time-based job scheduler in Unix-like operating systems, including Ubuntu. It allows users to schedule jobs (commands or scripts) to run periodically at fixed times, dates, or intervals. This section will cover the basics of how cron works and how to set up your first scheduled task.

Installing Cron

Ubuntu comes with cron pre-installed, so there’s no need to install anything extra for this article. However, if you’re on a different distribution that doesn’t have cron installed by default, you can usually install it via:

sudo apt-get update sudo apt-get install cron

Setting Up a Cron Job

To create or edit your crontab (cron table), use the following command:

crontab -e

This will open an editor where you can define your tasks. Here’s a basic syntax for adding a job to run every hour at minute 0:

0 * * * * /path/to/command_or_script.sh

Let’s break down what each field in the crontab entry means:

  • minute: The time of day, from 0 to 59.
  • hour: The hour of the day, from 0 to 23.
  • day_of_month: Day of the month, from 1 to 31.
  • month: Month of the year, from 1 to 12.
  • day_of_week: Day of the week (Sunday = 0 or 7).

You can specify multiple values for these fields by separating them with commas. For example, you might want your script to run every day at midnight and noon:

0 0,12 * * * /path/to/command_or_script.sh

Example Cron Job

Suppose we have a backup script located at /home/user/backup.sh that needs to be executed every Monday morning at 6 AM. The crontab entry would look like this:

0 6 * * 1 /home/user/backup.sh

After adding your cron job, save and exit the editor. Cron will automatically pick up any new or modified entries.

Viewing Scheduled Jobs

To see all current scheduled jobs, run:

crontab -l

This command lists out all of the tasks that are currently set to be executed by cron based on your crontab file.

Using watch for Continuous Command Execution

While cron is perfect for scheduling tasks at specific intervals over longer periods, sometimes you need to run a command continuously and see its output in real-time. The watch utility repeatedly executes a given command at an interval specified by the -n option. This can be very useful when monitoring system resources or checking the status of services.

Basic Usage

To monitor the CPU usage every two seconds, you would use:

watch -n 2 top -b | grep 'Cpu(s)'

Here, top -b generates a batch output suitable for parsing and grep 'Cpu(s)' filters out only the line containing CPU statistics. The -n option sets the interval to two seconds.

Advanced Features

The watch command has many options that can be used to customize its behavior further:

  • -d (or --differences): Highlights changes in output.
  • –interval=seconds: Set the time interval between invocations of the specified command, similar to -n.
  • –exec=command: Executes a command rather than running it through sh.

Creating Shell Scripts with Loops

For tasks that require more complex logic or need to run repeatedly but are not suitable for cron due to short intervals (less than a minute), shell scripts can be used in conjunction with loops. These scripts provide the flexibility of custom control structures within a loop, allowing you to perform operations such as checking conditions before running commands.

Example Script: Ping Every 30 Seconds

Here’s an example bash script that pings Google’s public DNS server every 30 seconds until manually interrupted:

#!/bin/bash while true; do date ping -c 1 google.com > /dev/null sleep 30 done

To make this script executable and run it, you would first save the above lines to a file named ping_script.sh, then:

chmod +x ping_script.sh ./ping_script.sh &

The trailing ampersand (&) runs the script in the background.

Conditional Execution

Scripts can also include conditional logic, such as checking if a service is up before running another command. For instance:

#!/bin/bash while true; do if curl --output /dev/null --silent --head --fail http://localhost:8080; then echo "Service is available" # Run your desired command here else echo "Service is unavailable, retrying in 1 minute..." sleep 60 fi done

This script continuously checks if a web server on http://localhost:8080 is reachable and performs actions based on the response.

Conclusion

Running commands at regular intervals can significantly enhance your productivity by automating routine tasks. This article covered three main methods to achieve this in Ubuntu:

  1. Cron jobs: For scheduling periodic, long-term tasks.
  2. Watch utility: Ideal for monitoring real-time changes or system statuses over short periods.
  3. Shell scripts with loops: Offers flexibility and control for complex logic and shorter intervals.

Whether you’re maintaining a server, automating backups, or monitoring application health, these techniques can be invaluable tools in your Linux administration arsenal. Experiment with different options to find the best fit for your needs.

Last Modified: 24/05/2019 - 14:30:51