DEV Community

Vishal Anand
Vishal Anand

Posted on

How to write cron jobs on AWS EC2 instance

Cron is a time-based job scheduler run on the server in the Unix-like operating system.
To perform such action we write cron expression made of five fields, followed by a shell command to execute.

First, we have to log in to AWS EC2 instance using CLI (Command Line Interface).
For log in, type:
ssh -i <.pem file> username@ip_address
After successfully log in, type:
crontab -e
then select any editor from the list (preferred nano).
Type cron command. For example:

  • * * * * * php /var/www/html/file/name.php Now save the changes. If you are using nano editor type Ctrl + x and Select Y and then press Enter. To list out all the running cron type: crontab -l
  • is used for every minute, every hour, etc. Here ”php” is shell command followed by file location of php script, separated by white space.

If you want to run nodejs script then type:

  • * * * * * node /var/www/html/nodejs/file/name.js Each from five stars represents a job:

How to write CRON jobs on AWS EC2 instance

Allowed special characters are:

Comma (,) – Commas are used to separate the item list.

For example:

Cron to run at minute 1 and 10 every hour
1,10 * * * * php /var/www/html/file/name.php
Cron to run at mid-night and mid-day
0 0,12 * * * php /var/www/html/file/name.php
Hyphen (-) – Hyphen defines range.

For example:

Cron to run at every minute from 1 minute through 10 minute, every hour
0-10 * * * * php /var/www/html/file/name.php
Cron to run at minute 0 past every hour from 6 AM through 6 PM
0 6-18 * * * php /var/www/html/file/name.php
Slash (/) – Slash defines step values.

For example:

Cron to run every 5th minute
*/5 * * * * php /var/www/html/file/name.php
Cron to run at minute 0 past every 6th hour
0 */6 * * * php /var/www/html/file/name.php
Sleep cron:

For example:

Cron to run every minute after sleep of 30 seconds

  • * * * * * sleep 30; php /var/www/html/file/name.php

For more examples visit: https://coderssecret.com/how-to-write-cron-jobs-on-aws-ec2-instance/

Top comments (0)