Class: FiberJob::Cron

Inherits:
Object
  • Object
show all
Defined in:
lib/fiber_job/cron.rb

Class Method Summary collapse

Class Method Details

.clear_allObject



59
60
61
62
63
# File 'lib/fiber_job/cron.rb', line 59

def self.clear_all
  redis.call('DEL', 'cron:jobs', 'cron:schedule')
  keys = redis.call('KEYS', 'cron:next_run:*')
  keys.each { |key| redis.call('DEL', key) } unless keys.empty?
end

.due_jobs(current_time = Time.now) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/fiber_job/cron.rb', line 38

def self.due_jobs(current_time = Time.now)
  job_names = redis.call('ZRANGEBYSCORE', 'cron:schedule', 0, current_time.to_f)

  job_names.map do |job_name|
    job_data_raw = redis.call('HGET', 'cron:jobs', job_name)
    job_data = job_data_raw ? JSON.parse(job_data_raw) : nil
    next unless job_data

    redis.call('ZREM', 'cron:schedule', job_name)

    job_data
  end.compact
end

.redisObject



5
6
7
# File 'lib/fiber_job/cron.rb', line 5

def self.redis
  @redis ||= RedisClient.new(url: FiberJob.config.redis_url)
end

.register(cron_job_class) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/fiber_job/cron.rb', line 9

def self.register(cron_job_class)
  job_name = cron_job_class.name
  cron_expression = cron_job_class.cron_expression

  redis.call('HSET', 'cron:jobs', job_name, JSON.dump({ 'class' => job_name,
                                                'cron' => cron_expression,
                                                'queue' => cron_job_class.new.queue,
                                                'registered_at' => Time.now.to_f }))

  unless redis.call('EXISTS', "cron:next_run:#{job_name}") > 0
    next_time = cron_job_class.next_run_time
    schedule_job(cron_job_class, next_time)
  end

  FiberJob.logger.info "Registered cron job: #{job_name} (#{cron_expression})"
end

.registered_jobsObject



52
53
54
55
56
57
# File 'lib/fiber_job/cron.rb', line 52

def self.registered_jobs
  jobs = redis.call('HGETALL', 'cron:jobs')
  # Convert array response to hash
  jobs = Hash[*jobs] if jobs.is_a?(Array)
  jobs.transform_values { |data| JSON.parse(data) }
end

.schedule_job(cron_job_class, run_time) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
# File 'lib/fiber_job/cron.rb', line 26

def self.schedule_job(cron_job_class, run_time)
  job_name = cron_job_class.name

  # Set next run time
  redis.call('SET', "cron:next_run:#{job_name}", run_time.to_f)

  # Add to sorted set for efficient scanning
  redis.call('ZADD', 'cron:schedule', run_time.to_f, job_name)

  FiberJob.logger.debug "Scheduled #{job_name} for #{run_time}"
end