Class: CronRunner

Inherits:
Object
  • Object
show all
Defined in:
lib/macaw_framework/core/cron_runner.rb

Overview

This module is responsible to set up a new thread for each cron job defined

Instance Method Summary collapse

Constructor Details

#initialize(macaw) ⇒ CronRunner

Returns a new instance of CronRunner.



7
8
9
10
# File 'lib/macaw_framework/core/cron_runner.rb', line 7

def initialize(macaw)
  @logger = macaw.macaw_log
  @macaw = macaw
end

Instance Method Details

#start_cron_job_thread(interval, start_delay, job_name, &block) ⇒ Object

Will start a thread for the defined cron job

Parameters:

  • interval (Integer)
  • start_delay (Integer?)
  • job_name (String)
  • block (Proc)


18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/macaw_framework/core/cron_runner.rb', line 18

def start_cron_job_thread(interval, start_delay, job_name, &block)
  start_delay ||= 0
  raise "interval can't be <= 0 and start_delay can't be < 0!" if interval <= 0 || start_delay.negative?

  @logger&.info("Starting thread for job #{job_name}")
  start_delay ||= 0
  thread = Thread.new do
    name = job_name
    interval_thread = interval
    unless start_delay.nil?
      @logger&.info("Job #{name} scheduled with delay. Will start running in #{start_delay} seconds.")
      sleep(start_delay)
    end

    loop do
      start_time = Time.now
      @logger&.info("Running job #{name}")
      block.call
      @logger&.info("Job #{name} executed with success. New execution in #{interval_thread} seconds.")

      execution_time = Time.now - start_time
      sleep_time = [interval_thread - execution_time, 0].max
      sleep(sleep_time)
    rescue StandardError => e
      @logger&.error("Error executing cron job with name #{name}: #{e.message}")
      sleep(interval)
    end
  end
  sleep(1)
  @logger&.info("Thread for job #{job_name} started")
  thread
end