ruby-on-railsherokuproduction-environmentclockwork

How to run clockwork script in production


I am using clockwork gem. I want to automatically delete all comments from comments table every day at midnight.

This app/clock.rb script is working as it supposed to in development env.:

require './config/boot'
require './config/environment'
require 'clockwork'

module Clockwork
  every(1.day, 'delete.comment', at: '00:00') {
    Comment.destroy_all
  }
end

when it's running on my local terminal with $ clockwork app/clock.rb.

So I deployed the app to Heroku. Later in a terminal, I run:

RAILS_ENV=production rails r app/clock.rb

as in this SO topic but only output is:

Running via Spring preloader in process 13973

and it quits to prompt and comments are still there (assuming the value in at: hash has passed).

This is my first individual project. My question is how to make this script running nonstop in production to remove comments automatically every day at midnight?
OR
more general:
how to run script nonstop in production.

I read this SO topic but the answers are not very thorough and first link above is neither, as for a beginner to understand.


Solution

  • You can create rake task and call form clock.rb

    every(1.day, 'name', at: '09:00')  do
        #Load task
        Rake::Task['comment:destroy'].invoke
    end
    

    rake task:

    lib/tasks/comment.rake

    namespace :comment do
      desc 'Destroy all comment'
      task destroy: :environment do
        Comment.destroy_all
      end
    end