set a cron job in linux code example
Example 1: create cron job from command line
#write out current crontab
crontab -l > mycron
#echo new cron into cron file
echo "00 09 * * 1-5 echo hello" >> mycron
#install new cron file
crontab mycron
rm mycron
Example 2: set cron job in ubuntu
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 cron
a) Our 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
b) Install cron package if necessary.
sudo apt-get install cron
c) Ensure that the cron service is running with the following command:
systemctl status cron
Example 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
Step 4: 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
Step 5: 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