Skip to content

Instantly share code, notes, and snippets.

@caok
Last active August 29, 2015 14:09
Show Gist options
  • Save caok/2a9b2f1769050101fc99 to your computer and use it in GitHub Desktop.
Save caok/2a9b2f1769050101fc99 to your computer and use it in GitHub Desktop.
ActiveJob in rails4
gem 'delayed_job_active_record'
bundle install

rails generate delayed_job:active_record
rake db:migrate

Rails 3 Mailers

# without delayed_job
Notifier.signup(@user).deliver

# with delayed_job
Notifier.delay.signup(@user)

# with delayed_job running at a specific time
Notifier.delay(run_at: 5.minutes.from_now).signup(@user)
class LongTasks
  def send_mailer
    # Some other code
  end
  handle_asynchronously :send_mailer, :priority => 20

  def in_the_future
    # Some other code
  end
  # 5.minutes.from_now will be evaluated when in_the_future is called
  handle_asynchronously :in_the_future, :run_at => Proc.new { 5.minutes.from_now }

  def self.when_to_run
    2.hours.from_now
  end

  def call_a_class_method
    # Some other code
  end
  handle_asynchronously :call_a_class_method, :run_at => Proc.new { when_to_run }

  attr_reader :how_important

  def call_an_instance_method
    # Some other code
  end
  handle_asynchronously :call_an_instance_method, :priority => Proc.new {|i| i.how_important }
end
RAILS_ENV=production bin/delayed_job start
RAILS_ENV=production bin/delayed_job stop
RAILS_ENV=production bin/delayed_job restart

Cleaning up

rake jobs:clear

capistrano

# for delayed job
after "deploy:stop",    "delayed_job:stop"
after "deploy:start",   "delayed_job:start"
after "deploy:restart", "delayed_job:restart"
after 'deploy:publishing', 'deploy:restart'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment