I have to fire off ad beacons from an SG app at specific points in a stream. In practice this means I can have over a dozen HTTP calls at once. I do not care about the responses.
Right now I have a task to handle the HTTP requests, and I create a new task for each request.
However I ran into a problem that plagued me in SDK1, where the task is garbage collected before the HTTP request is made.
To get around this I append the tasks to a list, then every now and then trim the list of completed requests. This feels like a kludge. Is there a best practice for spinning up a task and keeping it around until it completes, and only then allowing it to be garbage collected?
Here's the task code:
Sub dorequest()
url = m.top.url
? "[HTTP Request] ", url
request = createobject("roUrlTransfer")
port = createobject("roMessagePort")
msgfailurereason="n/a"
msgcode="n/a"
request.setmessageport(port)
request.setcertificatesfile("common:/certs/ca-bundle.crt")
request.initclientcertificates()
request.enablehostverification(false)
request.enablepeerverification(false)
request.retainbodyonerror(true)
request.seturl(url)
if (request.asyncgettostring())
while (true)
msg = wait(5000, port)
if (type(msg) = "roUrlEvent")
if (msg.getresponsecode() > 0 OR msg.getresponsecode() < 400)
? "[HTTP Request] SUCCESS. ",msg.getresponsecode()
else
msgfailureresponse = msg.getstring()
if msg.getresponsecode() <> invalid
msgcode = msg.getresponsecode()
end if
if msg.getfailurereason() <> invalid
msgfailurereason = msg.getfailurereason()
end if
? "[HTTP Request] REQUEST FAILED: ",url
? "[HTTP Request] CODE: ",msgcode, "REASON: ",msgfailurereason
end if
request.asynccancel()
exit while
else if (msg = invalid)
? "[HTTP Request] BEACON REQUEST FAILED: ",url
request.asynccancel()
end if
end while
end if
m.top.complete=true
End Sub
Here's my first stab at the code that uses it:
Sub fireBeacon(url as String)
? "Fire Beacon. ", url
task = CreateObject("roSGNode", "http_request")
task.url = url
task.control = "RUN"
'keep task from getting garbage collected
m.http_tasks.AddReplace(url,task)
cleanup_requests()
End Sub
sub cleanup_requests()
? "m.http_tasks 1: ",m.http_tasks.count()
for each t in m.http_tasks
? m.http_tasks[t].state
if m.http_tasks[t].complete
m.http_tasks.delete(t)
end if
end for
? "m.http_tasks 2: ",m.http_tasks.count()
end sub