簡単なRakeタスクを作ってみた

2025/01/06に公開

目的

WEB記事アプリケーションで、記事を予約入稿し時間が経つと自動で公開にしてくれる設定を作りたかった

実装部分

<scheduled_publish.rake>
namespace :articles do
  desc "Update scheduled articles to opened if their published_at has passed"
  task publish_scheduled: :environment do
    Article.where(status: :scheduled).where("published_at <= ?", DateTime.now).find_each do |article|
      article.update(status: :opened)
    end
  end
end

<schedule.rb>
set :output, "log/cron.log"
job_type :rbenv_runner, %q!eval "$(rbenv init -)"; cd :path && :bundle_command :runner_command -e :environment ':task' :output!
~~
every 10.minutes do
  rake "articles:publish_scheduled"
end

# 実行コマンド
RAILS_ENV=development bundle exec rake articles:publish_scheduled
# 実行ログ確認コマンド
tail -f log/development.log

Discussion