Class: Desiru::Jobs::Scheduler

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/desiru/jobs/scheduler.rb

Overview

Simple cron-like scheduler for Sidekiq jobs

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeScheduler

Returns a new instance of Scheduler.



13
14
15
16
17
# File 'lib/desiru/jobs/scheduler.rb', line 13

def initialize
  @jobs = {}
  @running = false
  @thread = nil
end

Instance Attribute Details

#jobsObject (readonly)

Returns the value of attribute jobs.



11
12
13
# File 'lib/desiru/jobs/scheduler.rb', line 11

def jobs
  @jobs
end

Instance Method Details

#clearObject

Clear all scheduled jobs



66
67
68
# File 'lib/desiru/jobs/scheduler.rb', line 66

def clear
  @jobs.clear
end

#job_info(name) ⇒ Object

Get information about a scheduled job



71
72
73
# File 'lib/desiru/jobs/scheduler.rb', line 71

def job_info(name)
  @jobs[name]
end

#running?Boolean

Check if scheduler is running

Returns:

  • (Boolean)


61
62
63
# File 'lib/desiru/jobs/scheduler.rb', line 61

def running?
  @running
end

#schedule(name, job_class:, cron:, args: [], **options) ⇒ Object

Schedule a job to run periodically

Parameters:

  • name (String)

    unique name for the scheduled job

  • job_class (Class)

    the job class to execute

  • cron (String)

    cron expression or simple interval

  • args (Array) (defaults to: [])

    arguments to pass to the job

  • options (Hash)

    additional options



25
26
27
28
29
30
31
32
33
34
# File 'lib/desiru/jobs/scheduler.rb', line 25

def schedule(name, job_class:, cron:, args: [], **options)
  @jobs[name] = {
    job_class: job_class,
    cron: cron,
    args: args,
    options: options,
    last_run: nil,
    next_run: calculate_next_run(cron, nil)
  }
end

#startObject

Start the scheduler



42
43
44
45
46
47
48
49
50
51
52
# File 'lib/desiru/jobs/scheduler.rb', line 42

def start
  return if @running

  @running = true
  @thread = Thread.new do
    while @running
      check_and_run_jobs
      sleep 1 # Check every second
    end
  end
end

#stopObject

Stop the scheduler



55
56
57
58
# File 'lib/desiru/jobs/scheduler.rb', line 55

def stop
  @running = false
  @thread&.join
end

#unschedule(name) ⇒ Object

Remove a scheduled job



37
38
39
# File 'lib/desiru/jobs/scheduler.rb', line 37

def unschedule(name)
  @jobs.delete(name)
end