Create CRON Task For Web Server Environment Example 

Yes you can create cron tasks in the web server environment which can be handy when you want to do background things you'd otherwise have to spin up a worker environment to do (at extra running cost).  You can create them in worker environments too but there's a simpler way provided by aws to define them in worker environments if preferred (google it).  The following has been tested on a web server environment only.

In the ".ebextensions" folder create a config file or add to your existing config file.  In this example the config file is called "project.config" (the name doesn't actually matter)

Add the following to it:

    command: "crontab -r || exit 0"
    command: "cat .ebextensions/my_cron_job.txt | crontab"

Note you must uses spaces not tabs in this file

Now create a file called "my_cron_job.txt" and add the following to it:

# The newline at the end of this file is extremely important.  Cron won't run without it.
# Run every 1 minute
* * * * * /usr/bin/php /var/app/current/my_php_file.php 
# End


There must be a blank line at the end of the file.  It may also be necessary to avoid blank lines earlier in the file (not checked).

If you are creating the file in windows add a space at the end of the cron definition (after the ".php" as windows will add a <CR> before the <LF> which linux doesn't like, but the space before it will let the line through.

Don't add "root" after the time definition to specify root user, it stops it working (it will execute as root anyway – you can see this in the log once its running)

If your php file "includes" any other file bear in mind you may need to provide the full path to the file as the php file is being called by cron in a different working directory.  In our case it wasn't necessary, but one to be aware of in case.  It may be possible to solve it by using the following (not tried but saw it somewhere): * * * * * cd /var/app/current/; /usr/bin/php /var/app/current/my_php_file.php

View cron log via SSH

sudo grep CRON /var/log/cron


Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.


Your email address will not be published.