In this post we will be going to explore hot to add cron job for root or other linux users on AWS Instance or Lightsail Instance. Ideally this stands true for other vm cloud or vps providers as well. In order to set a cron job we need to be familiar with parameters of cron command. If you are new and do not have much knowledge about cron, then you should read this post : Learn cron job in an easy way
1. AWS EC2 Linux Instance or Lightsail Linux Instance.
2. SSH access key to connect instance.
3. Root access.
3. Allowed port 22 in security group to connect from your ip.
1. SSH to your EC2 Instance
Login through ssh on your instance, your login user will be different than root. You can type below command to switch to root user.
$ sudo su
2. List cronjobs
You can list cronjobs through below command. It will list cronjobs of currently logged in user.
To list cronjobs of any specific linux user.
crontab -u alpha -l
Above command will list cronjob of alpha user.
3. Add cronjob through crontab
You can add cronjob through crontab command. The command will open a vi editor where in you can put your cronjob. A Crontab contains all the cronjobs.
$ crontab -e
When you run above command it will open in edit mode all the cron jobs of current logged in user. Once you type the command and press enter it will open vi editor. You need to press escape button and then i button on keyboard to edit any cronjob or add new. Once you update or add, press escape and then :wq to save your changes. A cron consists of expression(schedule) followed by command to run on that schedule. Let’s see syntax of cron first followed by some examples.
* * * * * commandtorun
Each * in (* * * * *) represents a schedule parameter in the order or minute, hour, day of month, month, day of week. * means every possible value that means if you keep schedule as * * * * * in the cronjob, it will run every minute. Let’s see some examples.
5 10 5 * * php /var/www/html/myproject/process.php
This cron will run on 5th of every month at 10:05.
*/5 * * * * php /var/www/html/myproject/new.php
This cron will run in every 5 minutes.
* * * * * sh /adminscripts/dbbackup.sh
This cron will run in every minute.
4. Add cron for non root or a specific linux user
You can add cronjob for a specific linux user as below.
crontab -u alpha -e
You will be allowed to add cronjob for any other user only if you have sudo rights else you may not eb able to add.