← Home
rails

Rails Generate job

Reference & Command Builder

Published: 2023-05-11
Author: Harrison Broadbent
Type: Reference & Command Builder

Rails Generate Job

Rails Generate Job (rails g job) is the generator for ActiveJob jobs. Jobs let you run code asyncronously, and are useful for things like billing charges, bulk-sending emails, or exporting large files.

This is what a freshly generated job looks like —

class ExampleJob < ApplicationJob
  queue_as :default
 
  def perform(*args)
    # Do something later
  end
end

The code inside #perform will be excecuted asyncronously, when you perform the job. There are two methods for performing jobs, #perform_now and #perform_later.

Calling #perform_now will start processing your job immediately. Calling #perform_later will enqueue your job for processing later (whenever that may be). You can optionally chain #set with #perform_later to indicate when your job should run —

# perform now
ExampleJob.perform_now
 
# perform ~later
ExampleJob.perform_later
 
# perform _after_ a certain time
ExampleJob.set(wait: 1.day).perform_later
 
# perform _at_ a certain time
ExampleJob.set(wait_until: Date.tomorrow.noon).perform_later

Command Builder for rails g job

rails g job 

Job Name

Generator Options

Runtime Options

# Command Options
❯ rails g job

Usage:
  rails generate job NAME [options]

Options:
      [--skip-namespace], [--no-skip-namespace]              # Skip namespace (affects only isolated engines)
      [--skip-collision-check], [--no-skip-collision-check]  # Skip collision check
      [--queue=QUEUE]                                        # The queue name for the generated job
                                                             # Default: default
  -t, [--test-framework=NAME]                                # Test framework to be invoked
                                                             # Default:

Runtime options:
  -f, [--force]                    # Overwrite files that already exist
  -p, [--pretend], [--no-pretend]  # Run but do not make any changes
  -q, [--quiet], [--no-quiet]      # Suppress status output
  -s, [--skip], [--no-skip]        # Skip files that already exist

# Command Description
Description:
  This generator creates an active job file at app/jobs