Search code examples
ruby-on-railsrubycronscheduled-tasksjobs

Difference between background jobs, rake tasks and cronjobs in Ruby on Rails?


I have just started exploring rake tasks and cronjobs in rails. I was confused about the comparison among them and what to you in which situation. As far as I know background job is something that is generated while application is running and task is something that we run through a command line. Suppose we are creating a user record using cronjob, we can do this with background job as well as simple task. Your sharing of knowledge is always appreciated!!.


Solution

  • A Rake task is just a script or small program implemented in Ruby using the Rake DSL. In the context of Ruby on Rails applications, Rake is traditionally used for tasks that “build” something or to manage dependencies. Common examples are database migrations, temp file cleanups, backups, and deployments. But in general rake tasks can be used for almost everything, even application-related, like data migrations, triggering emails, etc.

    A Cron job is a job scheduler on Unix-like operating systems (see Wikipedia). It is used to start recurring jobs at specific times (like each day at 12:00 or every first of a month) or in specific intervals (every 10 minutes). Cron is only a scheduler, it can start all kinds of command line scripts at specific times, for example, Rake tasks, database backups, or system checks.

    A background job in Ruby on Rails is usually implemented with ActiveJob or Sidekiq. You can schedule a job to run at a specific time or immediately when created. They are closer to your application than Rake or Cron and implemented directly in the application, using Ruby on Rails classes. You use a background job whenever there is a task triggered by a user that might take too long for the web requests and that instead can be done asynchronously. For example, sending an email, pulling data from an external API, and doing complex calculations after data was changed by the user. Another use-case is for tasks that can fail and that should be retried a couple of times.

    Tl;dr Use a Rake task – when you want to write a small script to manage our application. Use a Cron tasks when you want to run a script or task on a regular basis. Use background processing to do tasks in your application asynchronously to speed up web requests.