Sha256: a05f87d47fecae486fc9de4a9ed8ef8f5808afec710b2ef121f38c098901d372

Contents?: true

Size: 1.09 KB

Versions: 1

Compression:

Stored size: 1.09 KB

Contents

require 'mayu/loader'
require 'thread'

module Mayu
  class PeriodicLoader
    SHUTDOWN_KEY = :mayu_periodic_loader_shutdown
    def initialize(interval:, **options)
      @loaded_at = nil
      @loader = nil
      @interval = interval
      @options = options
      @lock = Mutex.new
      @thread = nil
    end

    attr_reader :loaded_at, :loader

    def start
      return if @thread
      @lock.synchronize do
        return if @thread
        reload
        @thread = Thread.new(&method(:thread))
      end
    end

    def shutdown
      @lock.synchronize do
        if @thread
          @thread[SHUTDOWN_KEY] = true
        end
        @thread = nil
      end
    end

    def reload
      @loaded_at = Time.now
      new_loader = Loader.new(user_completer: @loader&.user_completer, **@options).load
      @loader = new_loader
    end

    def thread
      loop do
        return if @thread[SHUTDOWN_KEY]
        @lock.synchronize do
          reload
        end
        sleep @interval
      rescue Exception => e
        $stderr.puts e.full_message
        sleep @interval
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
mayu-0.1.0.beta1 lib/mayu/periodic_loader.rb