1

Suppose there's a task

rake startupscript

that should run whenever the app boots, how can we automate that on heroku?

I know there's a heroku scheduler but that will run the task every 10 minutes instead of just once at boot. I also know of the Procfile and believe this can be a solution, although I do not yet know how to implement (and probably more importantly, I don't want to risk breaking anything else that can be configured via a Procfile, e.g. webserver etc). A lot of the Procfile docs focus on using it to alter web servers rather than app level rake tasks.

How can a rake task be made to run at boot?

stevec
  • 41,291
  • 27
  • 223
  • 311

1 Answers1

2

You can add something like this to Procfile before you start your application services

# Run pre-release-tasks here
release: bundle exec rails db:migrate
# Then run your application
web: bundle exec puma -t 5:5 -p ${PORT:-3000} -e ${RACK_ENV:-development}

Anything tagged as release will run before the startup script runs

https://devcenter.heroku.com/articles/release-phase

TheGeorgeous
  • 3,927
  • 2
  • 20
  • 33
  • Thanks very much, it works. `web: bundle exec puma -t 5:5 -p ${PORT:-3000} -e ${RACK_ENV:-development}` makes me a little nervous, I don't want to accidentally reconfigure things. Do you know if they're defaults? Also, it is possible to have multiple lines for 'release'? – stevec Nov 03 '20 at 05:57
  • 1
    Oh, that was just an example. You don't have to use `web` line – TheGeorgeous Nov 03 '20 at 06:03
  • Do you happen to know if the Procfile runs when the app is `restart`ed, or just after its very first build? – stevec Nov 03 '20 at 06:36
  • @stevec that is also mentioned in the link I shared. https://devcenter.heroku.com/articles/release-phase#when-does-the-release-command-run FWIU, it won't run when you restart the web server, only when something changes – TheGeorgeous Nov 03 '20 at 06:42
  • Do you know if an infinite rake task will run happily in the background (forever) if it's started on boot? If not, then I should ask another question on how to do that (I will link to it from here) – stevec Nov 03 '20 at 06:46
  • 1
    An infinite rake task? Sound like what you need is a background job, a cron job or a second service. You will need to provide more details. You could edit this question to include that too – TheGeorgeous Nov 03 '20 at 06:50
  • I got it working using your method above, and it runs every 10 seconds, but I'm a bit nervous if the app crashes then it won't start running the process every 10 seconds (or ever) unless the app is changed, then `git push heroku master` .. – stevec Nov 03 '20 at 07:19
  • Actually, I just tested, by running `heroku restart`, and it most certainly does continue running the infinite loop! (I'm not sure if it ran the Procfile again and start it or via some other means, but it definitely worked) – stevec Nov 03 '20 at 07:26