Skip to content

Instantly share code, notes, and snippets.

@ichi
Last active August 29, 2015 14:17
Show Gist options
  • Select an option

  • Save ichi/acb73eb4402756e7cdc3 to your computer and use it in GitHub Desktop.

Select an option

Save ichi/acb73eb4402756e7cdc3 to your computer and use it in GitHub Desktop.
active_jobでretry回数制限とか
# initializers/active_job.rb
module ActiveJob
module CountableRetry
extend ActiveSupport::Concern
included do
class << self
alias_method_chain :deserialize, :retry_config
end
alias_method_chain :serialize, :retry_config
attr_accessor :retry_wait, :retry_limit
attr_writer :retry_count
cattr_accessor :retry_limit, instance_accessor: false
end
module ClassMethods
def deserialize_with_retry_config(job_data)
job = deserialize_without_retry_config(job_data)
retry_config = job_data['retry']
job.retry_count = retry_config['count']
job.retry_limit = retry_config['limit']
job.retry_wait = retry_config['wait']
job
end
end
def serialize_with_retry_config
data = serialize_without_retry_config
retry_config = {
'count' => retry_count,
'limit' => retry_limit,
'wait' => retry_wait,
}
data.merge({'retry' => Arguments.send(:serialize_argument, retry_config)})
end
def retry_with_count(options = {})
merge_retry_config!(options)
self.retry_count = retry_count + 1
return if retry_limit && retry_count > retry_limit
if retry_interval
retry_job wait: retry_interval
else
retry_job
end
end
def merge_retry_config!(options = {})
self.retry_limit ||=
if options[:limit]
options[:limit].to_i
else
self.class.retry_limit
end
self.retry_wait ||= options[:wait].to_i if options[:wait]
end
def retry_count
@retry_count ||= 0
end
def retry_interval
retry_wait && retry_wait * retry_count
end
end
ActiveSupport.on_load(:active_job) do
Base.send :include, CountableRetry
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment