I have to use an external API to generate a screenshot. In the first step I trigger the generation of the screenshot and receive a job_id
. Than I have to wait and can download the screenshot with the given job_id
. Unfortunately I don't know how long I have to wait. Sometimes the result is ready after 10 seconds and sometimes not. If it is not ready the function image_url/1
returns nil
. If it is ready it returns the image URL.
Currently I use a sleep for 45 seconds which is suboptimal.
I don't understand how I can use the concept of recursion to achieve that the function generate_screenshot/1
, first runs new_job_id(url)
and than tries image_url/1
10 times with a 10 second sleep between or until it is not nil
.
How can I solve this with a recursion?
def generate_screenshot(url) do
job_id = new_job_id(url)
:timer.sleep(45000)
image_url(job_id)
end
defp new_job_id(url) do
# This function triggers a process on
# an external web server an returns
# the job_id of it.
12345
end
defp image_url(job_id) do
# This function fetches something from
# a webserver. The result is nil or
# a URL of an image.
[...]
end