弹性豆茎cron运行两次

时间:2013-08-07 12:45:27

标签: cron response elastic-beanstalk

我有一个关于弹性beanstalk和cron作业的应用程序。

设置cron的代码是

container_commands:
  01_some_cron_job:
    command: "echo '*/5 * * * * wget -O - -q -t 1 http://site.com/cronscript/' | crontab"
  leader_only: true

此脚本调用邮件发件人。我每次收到两条消息。

http://site.com/cronscript/的代码看起来像(php代码)

require_once('ses.php');
$ses = new SimpleEmailService(EMAIL_SHORTKEY, EMAIL_LONGKEY);
$m = new SimpleEmailServiceMessage();
$m->addTo('user@domain.com');
$m->setFrom('response_service@domain.com');
$m->setSubject('test message');
$m->setMessageFromString('', 'message content');
$send_emails=($ses->sendEmail($m));

当我从浏览器的地址栏中拨打http://site.com/cronscript/时,我会收到一条消息。

2 个答案:

答案 0 :(得分:3)

我相信正在发生的事情是,第一次部署应用时,AutoScaling选择一个实例作为领导者,并在该实例上创建新的cron作业。下次部署应用程序时,AutoScaling会选择另一个实例作为领导者。所以你最终在两个实例上使用相同的cron作业。

因此,基本测试将是ssh到所有实例并使用crontab检查其crontab -l内容

您可以通过删除实例上的旧cron作业来避免重复的cron作业,无论它是否是领导者。

container_commands:
  00_remove_old_cron_jobs:
    command: "crontab -r || exit 0"
  01_some_cron_job:
    command: "echo '*/5 * * * * wget -O - -q -t 1 http://example.com/cronscript/' | crontab"
    leader_only: true

Running Cron In Elastic Beanstalk Auto-Scaling Environment中所述:|| exit 0是必需的,因为如果计算机中没有crontab,crontab -r命令将返回状态代码> 0(错误)。如果其中一个container_commands失败,Elastic Beanstalk将停止部署过程。

虽然我个人从未遇到过在Elastic Beanstalk Instance上找不到crontab的情况。

您可以运行/opt/elasticbeanstalk/bin/leader-test.sh来测试它是否是领导者实例。

希望它有所帮助。

答案 1 :(得分:0)

我遇到了同样的问题,只是将用户从root更改为我使用eb ssh登录的用户,并且可以正常工作。 我的代码看起来像这样。

files:
"/etc/cron.d/mycron":
    mode: "000644"
    owner: ec2-user
    group: ec2-user
    content: |
        30 1 * * * echo $(date) >> /tmp/cron_start.log; /usr/local/bin/daily_script.sh >> /tmp/crons.log 2>&1;



"/usr/local/bin/daily_script.sh":
    mode: "000755"
    owner: ec2-user
    group: ec2-user
    content: |
        #!/bin/bash

        date > /tmp/date
        # Your actual script content
        /opt/python/run/venv/bin/python3 /opt/python/current/app/cronjob_files/email_data.py >> /opt/python/current/app/cron.logs 2>&1

        exit 0

...