Class: Schked::Adapters::ActiveRecord

Inherits:
Object
  • Object
show all
Includes:
JobRunStore
Defined in:
lib/schked/adapters/active_record.rb

Constant Summary collapse

SUPPORTED_ADAPTERS =
%w[PostgreSQL Mysql2 Trilogy].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(pool, logger: Logger.new($stdout)) ⇒ ActiveRecord

Returns a new instance of ActiveRecord.



24
25
26
27
28
29
30
# File 'lib/schked/adapters/active_record.rb', line 24

def initialize(pool, logger: Logger.new($stdout))
  # Accept either a ConnectionPool or a concrete adapter connection
  # (+ActiveRecord::Base.connection+) and normalize to the pool.
  @pool = pool.respond_to?(:with_connection) ? pool : pool.pool
  @logger = logger
  validate_adapter!
end

Instance Attribute Details

#adapter_nameObject (readonly)

Returns the value of attribute adapter_name.



21
22
23
# File 'lib/schked/adapters/active_record.rb', line 21

def adapter_name
  @adapter_name
end

#loggerObject (readonly)

Returns the value of attribute logger.



22
23
24
# File 'lib/schked/adapters/active_record.rb', line 22

def logger
  @logger
end

Instance Method Details

#claim(job_name, window_start) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/schked/adapters/active_record.rb', line 32

def claim(job_name, window_start)
  validate!(job_name, window_start)

  ts = window_start.is_a?(Time) ? window_start.to_i : Integer(window_start)
  run_at = Time.now.to_f
  claimer = SecureRandom.uuid

  @pool.with_connection do |connection|
    if postgres?
      postgres_claim(connection, job_name, ts, run_at, claimer)
    else
      mysql_claim(connection, job_name, ts, run_at, claimer)
    end
  end
rescue ArgumentError
  raise
rescue => e
  logger.error("Failed to claim AR job run with error: #{e.message}")
  raise
end

#cleanup(older_than) ⇒ Object



53
54
55
56
57
58
59
60
61
62
# File 'lib/schked/adapters/active_record.rb', line 53

def cleanup(older_than)
  cutoff = older_than.is_a?(Time) ? older_than.to_i : Integer(older_than)
  @pool.with_connection do |connection|
    connection.execute("DELETE FROM #{TABLE} WHERE window_start < #{connection.quote(cutoff)}")
  end
  nil
rescue => e
  logger.error("Failed to clean up AR job runs with error: #{e.message}")
  raise
end