How to set up Cron Job on Amazon EC2 Cloud Servers

July 6, 2021 . 2 MIN READ

Here I will show you how to set up a cron job on an Amazon Linux server. We used the basic Linux 64bit ami but these directions should work for any Linux web server

How to set up Cron Job on Amazon EC2 Cloud Servers

We used the basic linux 64bit ami but these directions should work for any linux web server

open a command prompt

type: which php
returns: /usr/bin/php

using the reponse from which php above, add the proper shebang to your php script like so:

#!/usr/bin/php -q

the  -q parameter makes it so you don’t get an email every time cron runs.

continuing from command prompt:

type: crontab -e

then use vim editor to add the following line to crontab to run  your php script every minute:

* * * * * /usr/bin/php /home/ec2-user/crontest.php

or every hour:

0 * * * * …

the five cron positions are as follows:

minute         0-59
hour           0-23
day of month   0-31
month          1-12
day of week    0-7 (sun = 0 or 7)

start a php file named crontest.php and enter the following contents:

———————-code—————————-
#!/usr/bin/php -q
<?php
//script to test cron on adam’s cloud server:
$message = “If ur reading this then the cron job worked!!!!nn”;

$myFile = “testFile.txt”;
$fh = fopen($myFile, ‘w’) or die(“can’t open file”);

fwrite($fh, $message);
$stringData = “Yay for cloud cron! script was home/ec2-user/crontest.phpn”;
fwrite($fh, $stringData);
fclose($fh);
?>
——————————————————–

start another php file named testFile.php. It will just be a blank txt file with no content at all.

Then upload crontest.php and testFile.php to /home/ec2-user and change permissions of both to 755 or 777 if 755 doesn’t work but 777 can cause a security issue.

Important note: it seems that if you change the regular crontab using crontab -e call that they files have to be in the user’s directory that you are in when making the call which in this case is user ec2-user

To get crontab-e to work, use following comand to switch users and try again:

su ec2-user

*/5 * * * * /usr/bin/php /var/www/html/cron.php

Leave a Reply

Your email address will not be published. Required fields are marked *