Create a Cron Task in Ubuntu 16.04

Cron jobs are an incredibly useful Linux tool aimed at saving you time by scheduling tasks within your server. A programmed cron task will execute commands within a script by the minute, day, week or month. They can be scheduled to do many tasks including backing up your server’s files nightly, updating inventory orders in a database or even compressing files for migrating. Repetitive tasks become a cinch when incorporating a cron job. While there are numerous ways to run a cron task, we will be using the crontab option that is inherent within Ubuntu to set up a nightly backup of our website.

Pre-flight

Log in to your Ubuntu 16.04 LTS server, preferably not as root if you aren’t altering anything on the server level.

Setting Up a Website Backup through Cron

Step 1: Update your server. As a best practice, we will update and upgrade our server with the following command.

apt-get update && apt-get upgrade

 

Step 2: Verify if the cron package is installed.
dpkg -l cronOur example output let’s us know that the cron package is installed, along with its version:
||/ Name Version Architecture Description
+++-=========================-=================-=================-========================================================
ii cron 3.0pl1-128ubuntu2 amd64 process scheduling daemon

Install cron package if necessary.
sudo apt-get install cron

Ensure that the cron service is running with the following command:
systemctl status cronExample Output:
* cron.service - Regular background program processing daemon
Loaded: loaded (/lib/systemd/system/cron.service; enabled; vendor preset: enabled)
Active: active (running) since Sat 2018-10-27 02:53:20 EDT; 5 days ago

 

Step 3: Configure the cron job. When you are logged in as your user, you are creating a cron job under that user. Creating a cron jobs owner is helpful when to know who is in charge of the cron as well as how to alter the cron job in the future.

crontab -e

The system asks which editor you’d like to use; this tutorial is using option 2 (vim.basic).

tom@host2:~$ crontab -e
no crontab for tom - using an empty one
Select an editor. To change later, run 'select-editor'.
1. /bin/ed
2. /usr/bin/vim.basic
3. /usr/bin/vim.tiny
Choose 1-3 []: 2

In this file, you’ll see # signs followed by the direction on how to use the file. Allow us a minute to explain the syntax needed to create a cron task.

# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed

Each set of digits designates the time for that section and follows the time set in your server The first set represents minutes, the next set hours, the next set day of the month and so on. You may be asking yourself what the asterisk mean. They represent every or all value for that set. So, if you put an asterisk on the month column, you’ll be telling the system to perform the tasks every month.

After the digits section is the /bin/sh and the type of file that should be executed, lastly, the final column assigns the command of which to run.

Backup Cron:
Let’s say you want to backup your website files daily. Our example uses 4 am since server traffic is low during this time. Take note of the .sh extension, indicating a bash script. Use the appropriate extension for your script. Be sure to save the script when exiting with :wq

crontab -e

After altering the /path/to/script/backup-script.sh path to match the location of your script, set the command in a new line, below the hashtag (#), like so:

# m h dom mon dow command
0 4 * * * /bin/sh /path/to/script/backup-script.sh

 

Step 4: Place Script in Path. Most importantly is the creation and placement of your script. With our example script we are creating a backup that will compress files and directories, indicated by the /SOURCE/DIRECTORY/. The /SOURCE/DIRECTORY/ needs to be alter to the directory and files you wish to save (sometimes a website’s default directory path is /var/www/html), while the /DESTINATION/DIRECTORY/file.zip indicates where the compressed backup are stored. We will name the script backup-script.sh, and afterwards, we will create the script in the location of /path/to/script/backup-script.sh.

vim backup-script.sh

#!/bin/sh
zip -9pr /DESTINATION/DIRECTORY/file.zip /SOURCE/DIRECTORY/

 

Note:
If you are running this script multiple times it will overwrite the file.zip each time, thus it runs it will only store one backup.

Set execute permissions this allows the system permission to run the script.

chmod +x backup-script.sh

When the time of execution has passed, check your /DESTINATION/DIRECTORY/ to see file.zip. YYou now have backups of your files running daily! It’s best to come up with a plan to offload your backups to another location other than your server. Pushing backups to an offsite location not only adds a layer of security but aids in saving server disk space. Check out our Cloud Object Storage for cost-effective storage solution that is accessible via API call. If you are having trouble with your cron check out our other helpful article, Troubleshooting: Cron Jobs.

 

Troubleshooting: Cron Jobs

Cron is a service for Linux servers that automatically executes scheduled commands. A cron job can be a series of shell commands, scripts, or other programs. Cron tasks or jobs can perform a variety of functions and once ran can send out an e-mail message to inform you of its completion or errors. If you receive an error, there are many ways to troubleshoot the cron task.  Use this article for troubleshooting assistance or a tutorial on the basics of cron jobs. If you would like to learn more about creating a cron job check out our Knowledge Base tutorials on the subject.

Checking Configurations with Crontab

From the command line, you can review the scheduled cron jobs by listing the crontab for the user. This command outputs the contents of the user’s crontab to the terminal.

As the user you can run:
crontab -l

As root, you can see any user’s crontab, by specifying the username.
crontab -l -u username

You can find some detailed information about how to format the cron jobs in the /etc/crontab file.  Below is the example within that file.  Each asterisk can be replaced with a number or to its corresponding field.  Or you can leave the asterisk in place to represent all possible numbers for that position.  For example, if left with all asterisk this means that the cron job will run every minute, all the time.

SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
# For details see man 4 crontabs
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed

 

Altering the E-mail Address of a Cron

Once initiated, a cron sends a notification to an email address, set within the MAILTO line of the crontab.

MAILTO="user@domain.com"

To edit the crontab, you can run the following commands as the user:

crontab -e

Or if logged in as root, you can type in the username for any of your users to see a scheduled task that they have created.

crontab -e -u usernameThese open the crontab of the user in the default editor. Typically the vim or nano command will open the file. Be aware that this similar to opening any other text file where you’ll save before closing.

The MAILTO line indicates where the execution status of a cron should be sent. The sending address will typically be the cron task creator’s username along with the server’s hostname. So an email’s sender address would follow this syntax, unixuser@serverhostname.com. If you don’t see an email right away, it may be a good idea to check your spam box.

Silenced Crons

Sometimes cron jobs are configured to either produce no output or have its output silenced, even if set with a MAILTO address. If you see a cron job listed with any of the following on end, it is a sign that the cron has output has been silenced. These send any output to the null device (the black hole on a Linux server). In cases like this, you’ll need to remove the line from the cron job script to generate an output.

&> /dev/null

2>&1 /dev/nullSome cron jobs are disabled entirely. These will have a “#” in front of the command, resulting ignored lines when executed. Remove the “#” to re-activate the cron job.

Verifying the Crond Service

Once you’ve confirmed the correct settings, it’s time to verify that the cron system is enabled and running. The three following commands can each be used to verify if the crond (the cron service) is running.

/etc/init.d/crond status

service crond status

systemctl status crond

After running any of the above commands, if you find the crond service is not running, you can start it with one of the following.

/etc/init.d/crond start

service crond start

systemctl start crond

/var/log/cron

Once you know that the cron is enabled, not silenced, and crond is running, then it’s time to check the cron log, located in the path of /var/log/cron.

cat /var/log/cron

Example Output:

Oct 2 23:45:01 host CROND[3957]: (root) CMD (/usr/local/lp/apps/kernelupdate/lp-kernelupdate.pl > /dev/null 2>&1)
Oct 2 23:50:01 host CROND[4143]: (root) CMD (/usr/lib64/sa/sa1 1 1)
Oct 2 23:50:01 host CROND[4144]: (root) CMD (/usr/local/maldetect/maldet --mkpubpaths >> /dev/null 2>&1)
In the log, you will see if, when and what user ran the cron. If initiated, you’ll see the date and time of execution followed by brackets of the individual cron number. This timestamp does not confirm that the script ran normally or at all, it only signifies when the cron system last ran the task. Beyond that, you may need to investigate the cron script itself or application-level configurations and their respective logs to ensure the code is executing correctly.

Other Cron Services

This article is merely an overview of the main crond service as there many other cron tasks services. The anacron system is a commonly used cron service that configures daily or hourly jobs, and can even be set to run at reboot. The logs for these kinds of tasks are within /var/log/cron, and are not executed by crond.

Other scheduled tasks, although also referred to as cron jobs, are not executed from the crond system. These cron jobs are often configured within the code or configuration of a website. To determine if executed, you’ll need to investigate other configurations and logs that the cron script interacts with.

As with all cron services, automated jobs can be manipulated to execute numerous daily tasks, so you don’t have to. Cron tasks can occasionally go awry even without altering them or years, but knowing where to look is half the battle in troubleshooting a cron job.

 

cPanel Error: Permission on “/usr/bin/crontab” are wrong (4755). Please set to 4755 [SOLVED]

Several cases have been reported where a broken symlink results in a permissions error when viewing or attempting to modify user cron jobs. Restoring the link resolves the issue.

Pre-Flight Check

  • These instructions are specifically for resolving the error: “Permission on ‘/usr/bin/crontab’ are wrong (4755). Please set to 4755”.
  • The error applies only to specific cPanel versions and CentOS operating systems, and appears to be most common for those using the x3 cPanel theme.
  • You will need root SSH access to the server to resolve the error.

Solution: Re-link the files

Fortunately, the fix for this error is quite simple. You can easily restore the link and resolve the error by running this command:

ln -s /usr/local/cpanel/bin/jail_safe_crontab /usr/bin/crontab

You now should be able to view and edit user cron jobs without error.

 

How to Display (List) All Jobs in Cron / Crontab

Servers can automatically perform tasks that you would otherwise have to perform yourself, such as running scripts. On Linux servers, the cron utility is the preferred way to automate the running of scripts. In this article we’ll cover how to view the jobs scheduled in the crontab list. For an introduction to Cron check-out our KB: How To: Automate Server Scripts With Cron. Knowing how to setup crontab is an important skill, but even if you’re not editing these knowing how to view them is important as well. Continue reading “How to Display (List) All Jobs in Cron / Crontab”