Class: Newshound::Jobs::Que

Inherits:
Base
  • Object
show all
Defined in:
lib/newshound/jobs/que.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#format_for_banner

Constructor Details

#initialize(logger: nil) ⇒ Que

Returns a new instance of Que.



8
9
10
# File 'lib/newshound/jobs/que.rb', line 8

def initialize(logger: nil)
  @logger = logger || (defined?(Rails) ? Rails.logger : Logger.new($stdout))
end

Instance Attribute Details

#loggerObject (readonly)

Returns the value of attribute logger.



6
7
8
# File 'lib/newshound/jobs/que.rb', line 6

def logger
  @logger
end

Instance Method Details

#job_counts_by_typeObject



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/newshound/jobs/que.rb', line 28

def job_counts_by_type
  results = ActiveRecord::Base.connection.execute(<<~SQL)
    SELECT job_class, error_count, COUNT(*) as count
    FROM que_jobs
    WHERE finished_at IS NULL
    GROUP BY job_class, error_count
    ORDER BY job_class
  SQL

  results.each_with_object({}) do |row, hash|
    job_class = row["job_class"]
    error_count = row["error_count"].to_i
    count = row["count"].to_i

    hash[job_class] ||= {success: 0, failed: 0, total: 0}

    if error_count.zero?
      hash[job_class][:success] += count
    else
      hash[job_class][:failed] += count
    end

    hash[job_class][:total] += count
  end
rescue => e
  logger.error "Failed to fetch job counts: #{e.message}"
  {}
end

#queue_statisticsObject



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/newshound/jobs/que.rb', line 12

def queue_statistics
  conn = ActiveRecord::Base.connection
  current_time = conn.quote(Time.now)
  beginning_of_day = conn.quote(Date.today.to_time)

  {
    ready: count_jobs("finished_at IS NULL AND expired_at IS NULL AND run_at <= #{current_time}"),
    scheduled: count_jobs("finished_at IS NULL AND expired_at IS NULL AND run_at > #{current_time}"),
    failed: count_jobs("error_count > 0 AND finished_at IS NULL"),
    finished_today: count_jobs("finished_at >= #{beginning_of_day}")
  }
rescue => e
  logger.error "Failed to fetch Que statistics: #{e.message}"
  {ready: 0, scheduled: 0, failed: 0, finished_today: 0}
end