Skip to content

Instantly share code, notes, and snippets.

@SokratisVidros
Last active March 17, 2016 10:46
Show Gist options
  • Save SokratisVidros/1be074e29325fcc0c5f8 to your computer and use it in GitHub Desktop.
Save SokratisVidros/1be074e29325fcc0c5f8 to your computer and use it in GitHub Desktop.
DJ - Play with delayed jobs
###############################################################################
# DJ - Play with Delayed Jobs
#
#    ('∀`)
#  _ ノ  )>_
# /.◎。/◎。/|
# | ̄ ̄ ̄ ̄ ̄|
#
# API:
#
# sample - Fetch a snapshot of the current Delayed::Job records
# echo - Pretty print the current desk
# monitor - Sample every 5 seconds until enter is pressed
# track(id) - Load the retrieved delayed job as current
# play - Invoke the current delayed job
# rewind - Reset last_error and attempts attributes of the current job
# scratch - Inspect the last error and handler of the current job
# eject - Delete the current delayed job
# eject_all - Delete all delayed jobs
#
###############################################################################
class DJ
PAD_ROW = "-%12s | %-30s | %-2s\n".freeze
def initialize
@deck = nil
@current = nil
sample
end
attr_reader :deck, :current
def sample
@deck = fetch_deck
echo
end
def echo
printf(PAD_ROW, "ID", "QUEUE", "ATTEMPTS")
deck.each do |row|
printf(PAD_ROW, row[0], row[1], row[2])
end
log("Size: #{deck.size}")
end
def monitor
t = Thread.new do
loop do
sample
sleep 5
end
end
gets
t.kill
end
def track(id)
@current = load_delayed_job(id)
@current
end
def play
current.try(:invoke_job)
end
def rewind
current.try(:update_columns, attempts: 0, last_error: 0)
end
def scratch
return unless current
info = {
handler: YAML.load(current.handler),
error: current.last_error.split("\n")[0..4]
}
log(info)
end
def eject
return unless current
current.delete
deck.delete_if { |t| t[0] == current.id }
@current = nil
end
def eject_all
log 'Are you sure you want to eject all your desk? (y/n)'
confirm = gets
return log('Phew!') unless confirm[0] == "y"
ids = deck.map { |j| j[0] }
Delayed::Job.where(id: ids).delete_all
log('Boom!')
end
private
def fetch_deck
Delayed::Job.order(attempts: :desc, created_at: :desc).pluck(:id, :queue, :attempts)
end
def load_delayed_job(id)
Delayed::Job.find(id)
rescue ActiveRecord::RecordNotFound => e
log('Not found!')
nil
end
def log(msg)
pp(msg);0
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment