Skip to content

Instantly share code, notes, and snippets.

@dsisnero
Created January 21, 2016 21:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dsisnero/c10a849c23773292edc1 to your computer and use it in GitHub Desktop.
Save dsisnero/c10a849c23773292edc1 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'concurrent'
module ReportCli
class Runner
attr_accessor :run_times, :reporter
# This method will not limit the number of threads in the pool. It will
# The thread pools in concurrent-ruby dynamically grow and shrink as needed.
# The best practice is to let the pool control its own size and not use
# thread pools directly. By default `Concurrent::Future` will use the global
# thread pool, which is almost always the best choice.
def run
# This will create an array of `Concurrent::Future` objects all of which
# will be executing in the background.
futures = self.run_times.collect do
# Within a thread pool the value of `self` will point to the thread
# pool. Although it is possible to access variables from the enclosing
# scope, the best practice is to pass an array of arguments into the
# future using the `args` option.
Concurrent::Future.execute(args: [self.reporter]) do |r|
# This will create a new reporter and execute it on a background
# thread using the global thread pool. The result it returns will be
# the final value of the future.
r.new.exec
end
end
# This will iterate over the running futures and collect their final
# values. This will allow this method to block until all the futures have
# completed.
results = futures.collect do |future|
# This call will block until the future is complete
future.value
# Alternatively, you can limit the length of time we block. This call
# will block for up to 10 seconds for the future to complete.
# future.value(10)
end
end
end
class Report
def initialize
# This connection will be shared by all instances of the Report class. It
# is critical that the connection object, whatever it is, be thread safe.
# If it is not then you'll need to create a new connection object in every
# instance of this class.
@conn = Config.connection
end
def end_point
"/api/v2/devices/#{Config.device_key}/reports.json"
end
def exec
payload = {}
payload[:screenshot] = Faraday::UploadIO.new("./#{shuffled_images}.jpg", 'image/jpeg')
@conn.post end_point, payload
end
def shuffled_images
["mat","pic","van"].shuffle.first
end
end
end
if $0 == __FILE__
runner = PreyReportCli::Runner.new
runner.run_times = 5
runner.caller = PreyReportCli::Report
runner.run
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment