Search code examples
ruby-on-railsrubyrakeforeman

Rails-way to execute one-off task on Rails server startup


I have Rails 4.2 application and I want to execute some one-off code when server starts.

My first approach was to use initializer in config/initializers to run the code. But in this case code is being executed also for all the rake tasks and Sidekiq process.

So I've created a rake task to run my code. Now I wonder how to execute it along with rails server startup. Of course, I can create a shell script that will execute my rake task and then start the server. But is there any rails-way to achieve this?

Foreman is another approach advised by SO, but it's not working for me as my task is not a daemon and the process terminates immediatelly after completion. Apparently all the processes in Procfile have to be daemonized.


Solution

  • Can be achieved with Foreman by running in the same process as daemonized task (e.g. with rails server).

    If one-off taks is rake lego:update_all

    Then corresponding Procfile is

    web: rake lego:update_all && rails s
    sidekiq: bundle exec sidekiq