Clockwork and delayed job and PostgreSQL

Clockwork is simple and very useful tool for scheduling tasks instead of using cron jobs in ruby.

First things first, add clockwork to your Gemfile:

gem 'clockwork'

Configuration is kept in config/clock.rb. It uses plain ruby DSL. Most amazing thing is to use custom handler which allows you to skip loading Rails environment and insert scheduled jobs directly into delyed job database table.

# Clockfile
require 'pg'
require 'yaml'
db = YAML.load_file(File.dirname(__FILE__) + "/database.yml")[ENV['RAILS_ENV'] || "development"]
conn = PGconn.connect(db['host'], nil, nil, nil, db['database'], db['username'], db['password'])

require 'clockwork'
include Clockwork


handler do |job|
  db_time = Time.now.utc.strftime("%Y-%m-%d %H:%M:%S")
  handler = "--- !ruby/object:ScheduledJob \njob: #{job}\n"
  conn.exec("INSERT INTO \"delayed_jobs\" (\"failed_at\", \"locked_by\", \"created_at\", \"handler\", \"updated_at\", \"priority\", \"run_at\", \"attempts\", \"locked_at\", \"last_error\") VALUES(NULL, NULL, '#{db_time}', '#{handler}', '#{db_time}', 0, '#{db_time}', 0, NULL, NULL)")
end

every(30.minutes, 'reactivate_paid_accounts')
# and more every blocks with definitions

And finally example of ScheduledJob:

# app/workers/scheduled_job.rb
class ScheduledJob
  attr_accessor :job
  SUPPORTED_JOBS = { 
                     :reactivate_paid_accounts    => 'Account.reactivate_paid'           
  }

  def initialize(job)
    self.job = job
    unless SUPPORTED_JOBS.has_key?(job.to_sym)
      raise "Unsupported scheduled action - #{job}"
    end
  end

  def perform
    klass, method = SUPPORTED_JOBS[job.to_sym].split('.')
    Kernel.const_get(klass).send(method.to_sym)
  end

  def display_name
    "Job/#{job}"
  end
end
Filed under  //   cron   delayed_job   postgresql   ruby  

Comments (0)

Leave a comment...

About

Web developer. Visit my links. Follow me on twitter.