0

I want to do something like the following: when a user clicks on a button, I send an ajax request to a server and a server starts doing a background IO operation while the user immediately receives a response says "it's started". That's it for the user.

On the server that background operation is going on. The operation should execute, say, 10 times in 10 minutes. It's something like periodic polling a status of something, say, a database. In the status has changed in less than 10 minutes, the operation should stop immediately, so it can be 1 minute or 3 minutes. Otherwise the operation keeps going. And at most it's 10 times within 10 minutes.

I surely don't want to use any third-party libraries because I know I can do that by the means of pure ruby or Rails. It doesn't matter that it's more difficult.

How can I do that?

I know, I should create a Thread, but how exactly should I do that part "constantly polling a status of something during 10 minutes at most once in a minute, at most 10 times and if the some condition is true then you're done, finish right away."

Note that's a simplified version of what I want but the idea is what I've described.

Alan Coromano
  • 24,958
  • 53
  • 135
  • 205
  • You can use `ActiveJob`. Look at http://stackoverflow.com/questions/25798013/how-do-i-schedule-recurring-jobs-in-active-job-rails-4-2 – Amit Badheka Jun 24 '16 at 09:11

1 Answers1

1

The following code seems like what you are after:

sleep_time = 60 # seconds
attempt = 0
max_attempts = 10
while (attempt < max_attempts)
  condition_met = check_condition()
  break if(condition_met)
  attempt += 1
  sleep(sleep_time)
end

Depending on your server, spawning a thread may be important. For example, if you server is only running on one thread, and you run the above code, your server will halt during the sleep times. That is, the server will not respond to any subsequent requests. If you spawn a thread, only the thread will sleep, but the main server process will continue. I can't say much more unless you provide details about your server. Is it WEBrick? thin?

As far as your comments about a user clicking a button to trigger this action, this can be as simple as an HTTP POST request to some Ruby on Rails controller you have implemented. It can tell the user the operation is ongoing if the request succeeds.

apoh
  • 31
  • 4