brandonhilkert / sucker_punch

Sucker Punch is a Ruby asynchronous processing library using concurrent-ruby, heavily influenced by Sidekiq and girl_friday.
MIT License
2.64k stars 114 forks source link

ActiveJob future support #172

Closed cshupp1 closed 8 years ago

cshupp1 commented 8 years ago

Currently, in sucker_punch_adapter.rb, the class SuckerPunchAdapter has the following method and implementation:

        def enqueue_at(job, timestamp) #:nodoc:
          raise NotImplementedError
        end

This means when using with ActiveJob (rails 4.2.x) that syntax like this:

ArtifactDownloadJob.set(wait_until: 5.seconds.from_now).perform_later

will not function.

Here is a monkey patch that works in JRuby. I have the following initializer file 'sucker_punch.rb':

require 'sucker_punch/async_syntax'

java_import 'java.util.Timer' do |p, c|
  'JTimer'
end

java_import 'java.util.TimerTask' do |p, c|
  'JTimerTask'
end

class TimerTask < JTimerTask

  def set_runnable(task_lambda)
    @lamb = task_lambda
  end

  def run
    @lamb.call
  end

end

module ActiveJob
  module QueueAdapters
    class SuckerPunchAdapter
      class << self
        def enqueue_at(job, timestamp) #:nodoc:
          time = java.util.Date.new(timestamp * 1000)
          timer = JTimer.new(job.to_s)
          timer_task = TimerTask.new
          timer_task.set_runnable(->{JobWrapper.new.async.perform job.serialize })
          timer.java_send(:schedule,[JTimerTask.java_class, java.util.Date.java_class],timer_task, time)
        end
      end
    end
  end
end

Syntax like:

ArtifactDownloadJob.set(wait_until: 5.seconds.from_now).perform_later

works in JRuby.

Cris

brandonhilkert commented 8 years ago

This is implemented in the upcoming Rails 5 release. Thanks for the code. Hopefully someone will find it useful. Previous versions used celluloid and I submitted a PR to have it supported but it was not accepted.

cshupp1 commented 8 years ago

This impl leaks. Please see this updated impl if you are using this lib in JRuby:

https://github.com/brandonhilkert/sucker_punch/issues/181