Skip to content

Instantly share code, notes, and snippets.

@oprypin
Forked from aaaScript/api_monitor_uninterrupted.cr
Created October 23, 2020 23:01
Show Gist options
  • Save oprypin/0174dee7f56fe033382db99af335dff2 to your computer and use it in GitHub Desktop.
Save oprypin/0174dee7f56fe033382db99af335dff2 to your computer and use it in GitHub Desktop.
Testing a way to have background api monitoring
# TODO: Write documentation for `HttpTest`
require "http"
require "json"
module HttpTest
VERSION = "0.1.0"
class API
def initialize(@host = "yesno.wtf", @port = 443)
@client = HTTP::Client.new(@host, @port, tls: true)
@ch = Channel(JSON::Any).new
spawn do
loop do
@ch.send(p! invoke_wtf_get_request)
sleep 1.second
end
end
end
def invoke_wtf_get_request
JSON.parse(@client.get("/api").body)
end
# https://gist.github.com/lbarasti/dab35d474ff55c68fdbb985a1d6147c9
Cache = Hash(Symbol, JSON::Any?).new
def get_wtf()
# Basically I want to get the request instantly, since it's in the background, so there's no latency to my main loop
# However, if the response doesn't come in time, just get the cached response
select
when v = @ch.receive
Cache[:wtf] = v
else
Cache[:wtf]
end
end
end
api = API.new
# Trying to see if I can get the while loop to spam text, while still getting uptodate API requests
loop do
puts "This text should be spamming the terminal, except it's help up with the api request"
begin
p api.get_wtf()
rescue KeyError
puts "Oh no"
end
sleep 0.1.seconds
end
# TODO: Put your code here
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment