Step 5: Create a Cron Job

Objective: Create a cron job for your backup script.

Now that you have a simple backup script, you want to run it periodically to ensure that your data is copied to another part of your VPS to keep it safe from accidental deletion.

Use A Beginners Guide To Cron Jobs and Creating a custom Cron Job to help you.

Build a Daily Cron Job

You will use the crontab application to install, remove, or edit cron jobs.

  1. Edit the cron jobs.

  2. Choose a time to run the script.

    • You should perform the backup when the system has low usage, such as when most of your users sleep.

    • Pick a time between 02:00 to 05:00.

  3. Build your cron job. This example runs at 03:00 daily.

    0 3 * * * <command-to-execute>
  4. List the cron jobs to verify that they were installed correctly.

    crontab -l

Testing your Cron Job

It is not easy to test cron jobs that run infrequently. You need to know two things:
(1) Did it run, and (2) did it run correctly.

  • You can run a cron job manually using Webmin:
    Webmin -> System -> Scheduled Cron Jobs

  • The output will display to the browser.

Another method is to log the output data to a file instead of to the screen. You can use this information to determine if it ran and if it produced expected data.

  • You can configure a command to send standard output (stdout) results to a file instead of the screen using > output-file:

    command > /path/to/output.txt
    # shell commands
    ls -lh > dir-listing.txt
    ./ > /tmp/output.txt
    # from a cron job
    0 3 * * * bash /root/ > /var/user-backups/backup-log.txt