Setup cronjob & queue in Elastic Beanstalk with Laravel
This is basically part-2 continue from Setup Laravel 5 in Amazon Elastic Beanstalk.
In most cases, we need to run some long process tasks in background, by either cronjob or queue.
Here I'll demostrate both.
Create a worker tier
We need to separate normal http operation from long process background tasks. So let's create a worker environment
eb create <environment> -t worker
Post hook after
First, create a directory in your project root
From now onward, I assume the current directory is in project root
Setup queue with supervisor & sqs
First you need to create a .config file
Where the supervise.sh you can download here
(credit to Günter Grodotzki)
Once you done this, you must add an environment variable in your elastic beanstalk console (worker tier only) "SUPERVISE=enable" to activate
Because you don't want the webapp environment to listen to the queue, thus this variable is used to identify which environment need to run this.
Create a queue
Create a queue in SQS console, then copy the URL to environment variable, e.g.
For how to use queue in laravel, refer here
Create a file named cron.config
Place this 2 files in .ebextensions. Again, same as supervise, you need to add
INS_CRONTAB environment variable in worker tier, and set the value to
One thing to take note, whenever the environment scale up to multiple server, your crontab may run multiple times, thus, I suggest that
create a table (e.g.
cronjob) in database, and add 2 attributes:
Thus, in your php script, you only run those job with
null, to avoid duplication.
Deploy your app
eb deploy <worker environment>