Here I am going to explain the simple steps to write your own Cron Jobs on AWS EC2 Server.
a. First, you have to Log in to your AWS EC2 instance
b. Run the below command
$ crontab -e
When you run Crontab command for the first time you will get some of the existed editors options to open
- /bin/ed
- /bin/nano
- /usr/bin/vim.basic
- /usr/bin/vim.tiny
Choose 1-4?
Select option 2 and enter.
Now you will get an editor to add Cron Jobs.
c. Add your every file paths/function paths which you want to schedule.
Note that you should specify single file path per line
For example:
0 10 * * * php /var/www/public_html/api/src/cronjob/notification.php
OR
0 10 * * * /bin/php /var/www/public_html/api/src/cronjob/notification.php
Here I am mentioning about PHP file path which sends notifications to the users on every day 10:00am.
- First term is Cron expression i.e 0 10 * * *
Cron Expression Examples:
* * * * * // Run every minute. ex: for 5 mins => */5 * * * *
0 * * * * // Run on the hour, every hour ex: every 2hrs => * */2 * * *
0 23 * * * // Run at 11 p.m. every day
0 0,12 * * 6 // Run at midnight and midday every Saturday
30 2 */2 * * // Run every second day at 2.30 a.m.
5 stars are explained below:
1st star: Minute (ranges from 0-59)
2nd star: Hour (ranges from 0-23)
3rd star: Day (ranges from 1-31)
4th star: Month(ranges from 1-12)
5th star: Day-of-week (0-7. 0 & 7 is Sun. 1-Mon, 2-Tue…etc)
- Second term is PHP command path. I.e php or /bin/php
- Third term is PHP file Path i.e /var/www/public_html/api/src/cronjob/notification.php
Command path will change depends on the programming language.
d. Once you enter your Cron Job Commands you have to save it.
To save type Cntrl+x and Select ‘Y’ and Enter.
e. To check whether your Cron Jobs is saved or not, run the below command.
$crontab -l
Now you can see your Cron Job file which has all your Cron Jobs.
For testing, you can schedule a task for a minute and check.
Send an email with the output every time the cron job runs.
You can have cron send an email every time it runs a command which produces output. If you do not want an email to be sent for an individual cron job, you can redirect the command’s output to /dev/null. For example: mycommand >/dev/null 2>&1