How do I setup and use Laravel Scheduling on AWS Elastic Beanstalk?

后端 未结 3 1233
日久生厌
日久生厌 2021-02-05 15:07

Scenario

As a fairly new user of Laravel and Elastic Beanstalk I soon found my self in the need to schedule operations, like most of us do.

In the past I had a

3条回答
  •  一向
    一向 (楼主)
    2021-02-05 15:48

    A simpler approach is to use the new Periodic Tasks feature. Using the .ebextensions for cron jobs may lead to multiple machines running the same job or other race conditions with auto-scaling.

    Jobs defined in cron.yaml are loaded only by the Worker environment and are guaranteed to run only by one machine at a time (the leader). It has a nice syncing mechanism to make sure there's no duplication. From the docs:

    Elastic Beanstalk uses leader election to determine which instance in your worker environment queues the periodic task. Each instance attempts to become leader by writing to an Amazon DynamoDB table. The first instance that succeeds is the leader, and must continue to write to the table to maintain leader status. If the leader goes out of service, another instance quickly takes its place.

    Creating a Cron for a Single or Multiple Workers

    Place cron.yaml in the root of the project:

    version: 1
    cron:
      - name: "schedule"
        url: "/worker/schedule"
        schedule: "* * * * *"
    

    One thing to take into consideration is that in Beanstalk periodic tasks are designed to make an HTTP POST request to a URL in your application that in turn triggers the job you want to run. This is similar to how it also manages queues with SQS.

    For Laravel

    For Laravel specifically, you may create the routes and controllers to handle each scheduled job. But a better approach is to use Laravel's scheduler and have a single route that you call every minute.

    This package will create those routes automatically for you https://github.com/dusterio/laravel-aws-worker

    Troubleshooting Permissions

    If you are running into trouble with the DynamoDB create Leader Table permissions when triggering a deploy from CodePipeline, it's because the CodePileline service role needs dynamodb:CreateTable. For instructions check these StackOverflow Question

    Official Elastic Beanstalk Periodic Tasks Docs

提交回复
热议问题