如何编写 cron 作业
How to write the cron job
我正在尝试在开发环境中不使用 "Whenever" 来设置 cron 作业。
我检查了日志,cron 似乎每 2 分钟工作一次,但没有发送邮件...
如何正确编写 cron 作业?
models/box.rb:
def self.reminder_mail
@boxes = Box.all
@boxes.each do |box|
if box.status == "PENDING"
NoticeMailer.sendmail_reminder(box).deliver
end
end
end
定时任务
*/2 * * * * ubuntu /home/ubuntu/workspace/box/reminder_mail
定时日志
Feb 25 11:10:01 ubuntu-xenial CRON[4599]: (ubuntu) CMD (ubuntu /home/ubuntu/workspace/box/reminder_mail)
Feb 25 11:10:01 ubuntu-xenial CRON[4598]: (CRON) info (No MTA installed, discarding output)
Feb 25 11:12:01 ubuntu-xenial CRON[4605]: (ubuntu) CMD (ubuntu /home/ubuntu/workspace/box/reminder_mail)
有一个变通方法,您可以实施 API 并使用 curl 在方法内使用自定义授权执行它,只是为了授权请求
然后在您的 crontab 中添加 curl 请求
*/2 * * * * curl --silent {you can spesify if it was POST,GET..etc} http://example.com/{your API path}
您的 cronlog 正在给您解释:您的开发系统中没有 MTA。 MTA 代表 Mail Transfer Agent,这是一种系统服务,可以像 cron 作业一样中继客户端发送的电子邮件。
如果可以,请安装和配置 postfix,这是一种非常流行的 MTA。
更新
你的 cron 文件是错误的,把 RAILS_ENV=production 改成第一个,像这样 RAILS_ENV=production rake reminder_task:reminder_email
.
此外,如果您的项目正在使用捆绑器,请使用 RAILS_ENV=production bundle exec rake reminder_task:reminder_email
— 这将允许 运行 您的 rake 任务可以访问所有必需的 gem 等。我认为您不必更改工作目录,都不是。相反,在 cron 文件中放入这样一行:
HOME=/path/to/your/project
我解决了这个问题!
重要的是在我的情况下 /home/ubuntu/.rbenv/shims
直接将 rake PATH 写入 PATH 而不要在 cron 作业中提及。
*/2 * * * * ubuntu cd /home/ubuntu/workspace/box && RAILS_ENV=development bundle exec rake reminder_task:reminder_mail >> /home/ubuntu/workspace/box/log/cron.log
我正在尝试在开发环境中不使用 "Whenever" 来设置 cron 作业。 我检查了日志,cron 似乎每 2 分钟工作一次,但没有发送邮件... 如何正确编写 cron 作业?
models/box.rb:
def self.reminder_mail
@boxes = Box.all
@boxes.each do |box|
if box.status == "PENDING"
NoticeMailer.sendmail_reminder(box).deliver
end
end
end
定时任务
*/2 * * * * ubuntu /home/ubuntu/workspace/box/reminder_mail
定时日志
Feb 25 11:10:01 ubuntu-xenial CRON[4599]: (ubuntu) CMD (ubuntu /home/ubuntu/workspace/box/reminder_mail)
Feb 25 11:10:01 ubuntu-xenial CRON[4598]: (CRON) info (No MTA installed, discarding output)
Feb 25 11:12:01 ubuntu-xenial CRON[4605]: (ubuntu) CMD (ubuntu /home/ubuntu/workspace/box/reminder_mail)
有一个变通方法,您可以实施 API 并使用 curl 在方法内使用自定义授权执行它,只是为了授权请求
然后在您的 crontab 中添加 curl 请求
*/2 * * * * curl --silent {you can spesify if it was POST,GET..etc} http://example.com/{your API path}
您的 cronlog 正在给您解释:您的开发系统中没有 MTA。 MTA 代表 Mail Transfer Agent,这是一种系统服务,可以像 cron 作业一样中继客户端发送的电子邮件。
如果可以,请安装和配置 postfix,这是一种非常流行的 MTA。
更新
你的 cron 文件是错误的,把 RAILS_ENV=production 改成第一个,像这样 RAILS_ENV=production rake reminder_task:reminder_email
.
此外,如果您的项目正在使用捆绑器,请使用 RAILS_ENV=production bundle exec rake reminder_task:reminder_email
— 这将允许 运行 您的 rake 任务可以访问所有必需的 gem 等。我认为您不必更改工作目录,都不是。相反,在 cron 文件中放入这样一行:
HOME=/path/to/your/project
我解决了这个问题!
重要的是在我的情况下 /home/ubuntu/.rbenv/shims
直接将 rake PATH 写入 PATH 而不要在 cron 作业中提及。
*/2 * * * * ubuntu cd /home/ubuntu/workspace/box && RAILS_ENV=development bundle exec rake reminder_task:reminder_mail >> /home/ubuntu/workspace/box/log/cron.log