I have a weird problem with aRuby program I’m writing.
Basically the idea is for the program to run constantly in the background. The program checks my browser history every 30 seconds and uploads any new history items to a server.
# client.rb
history = HistoryUploader.new(Chrome)
# Run everything
loop do
history.run
sleep 30
end
The important part of the HistoryUploader class looks like this
class HistoryUploader
def run
upload_history until local.last_seen_history_item == server.last_seen_history_item
end
def upload_history
# POST batches of history items to the server
end
end
The main problem I see with this code is that if HistoryUploader.run takes more than 30 seconds to complete (which it very well may since it is sending multiple http requests), the outside loop in client.rb will attempt to call run again and I could get parallel requests going to the server which would really confuse things.
Is there a way that I can block the run method from being called twice until it has finished?
I would use a request queue which executes requests one after another. You can also put a simple boolean flag inside HistoryUploader e.g. @is_uploading:
If you really want to block the main loop until the uploading is finished you can dispatch a thread and wait for it to finish using join: