Skip to content

Instantly share code, notes, and snippets.

@moiristo
Created May 9, 2014 09:23
Show Gist options
  • Save moiristo/7ff5deff05ab1b7789f0 to your computer and use it in GitHub Desktop.
Save moiristo/7ff5deff05ab1b7789f0 to your computer and use it in GitHub Desktop.
A simple ruby script to push jobs from the crontab to Delayed Job (Rails Postgres version)
#!/usr/bin/env ruby
require 'yaml'
require 'pg'
# Usage
if ARGV.size == 0
puts "Usage: script/dj_client WorkerName arg1 arg2"
exit(0)
end
# Get the environment
environment = ENV['RAILS_ENV'] || 'development'
# Get the worker
worker_name = ARGV[0]
worker_file = worker_name.gsub(/([a-z\d])([A-Z])/,'\1_\2').downcase
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'app', 'workers', worker_file))
worker = Object.const_get(worker_name).new(*ARGV[1..-1])
# Setup db connection
config = YAML.parse(File.read(File.expand_path(File.join(File.dirname(__FILE__), '..', 'config', 'database.yml')))).to_ruby[environment]
database = config['database']
host = config['host']
port = config['port'] || 5432
username = config['username'].to_s if config['username']
password = config['password'].to_s if config['password']
dbh = PG.connect(host, port, nil, nil, database, username, password)
# Get the current time in db format
db_time = Time.now.strftime("%Y-%m-%d %H:%M:%S")
# Push job
dbh.prepare('djstatement', 'insert into delayed_jobs (failed_at, locked_by, created_at, handler, updated_at, priority, run_at, attempts, locked_at, last_error) values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)')
dbh.exec_prepared('djstatement', [nil, nil, db_time, worker.to_yaml, db_time, 0, db_time, 0, nil, nil])
dbh.close
# Report
puts "Pushed job #{worker_name}#{" with arguments: #{ARGV[1..-1].inspect}" if ARGV.size > 1}"
@moiristo
Copy link
Author

moiristo commented May 9, 2014

Notes:

  • Requires the pg gem
  • Requires config/database.yml
  • Expects workers to be in RAILS_ROOT/app/workers
  • Sets the environment based on RAILS_ENV

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment