Sha256: fa7b2af3e91376b37239c8f5f659bcbcc7470e25e2a803d43f60a009b0730be1

Contents?: true

Size: 1.84 KB

Versions: 4

Compression:

Stored size: 1.84 KB

Contents

require 'timeout'
require 'active_support/dependencies'
require 'active_support/core_ext/numeric/time'
require 'active_support/core_ext/class/attribute_accessors'
require 'active_support/hash_with_indifferent_access'
require 'active_support/core_ext/hash/indifferent_access'
require 'logger'
require 'benchmark'

module Cron
  class Worker # rubocop:disable ClassLength
    DEFAULT_LOG_LEVEL = 'info'.freeze

    cattr_accessor :logger, :default_log_level

    def self.reset
      self.default_log_level ||= DEFAULT_LOG_LEVEL
    end

    def self.reload_app?
      defined?(ActionDispatch::Reloader) && Rails.application.config.cache_classes == false
    end

    def initialize(options = {})
      super()
      @exit = options[:exit_on_complete].presence
    end

    # Every worker has a unique name which by default is the pid of the process. There are some
    # advantages to overriding this with something which survives worker restarts:  Workers can
    # safely resume working on tasks which are locked by themselves. The worker will assume that
    # it crashed before.
    def name
      @name ||= "CronServer:#{Socket.gethostname} pid:#{Process.pid}"
    end

    def start # rubocop:disable CyclomaticComplexity, PerceivedComplexity
      trap('TERM') { stop }
      trap('INT') { stop }

      say 'Starting cron jobs server'

      self.class.lifecycle.run_callbacks(:execute, self) do
        loop do
          sleep Cron::Server.find_or_create_server.execute
          break if stop?
        end
      end

      say 'Exiting cron jobs server...'
    end

    def stop
      @exit = true
    end

    def stop?
      !!@exit
    end

    def say(text, level = default_log_level)
      text = "[CronServer(#{name})] #{text}"
      return if logger.blank?

      logger.send(level, "#{Time.now.strftime('%FT%T%z')}: #{text}")
    end
  end
end

Cron::Worker.reset

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
web47core-0.1.3 lib/app/jobs/cron/worker.rb
web47core-0.1.2 lib/app/jobs/cron/worker.rb
web47core-0.1.1 lib/app/jobs/cron/worker.rb
web47core-0.1.0 lib/app/jobs/cron/worker.rb