I am making a program in Delphi that checks urls to see if they are up. The problem is that this action can take bit of time on some websites. I would like it to give up after about 10 seconds. My question is there a way to stop the check after a certain amount of time and move on to the next item in the list to be checked?
update sorry about not putting the code. Still trying to pin down how much code is need and not in questions.
procedure TWebSiteStatus.Button1Click(Sender: TObject);
var
http: TIdHTTP;
url: string;
code: integer;
i: integer;
begin
for i := 0 to Memo1.Lines.Count - 1 do
begin
url := 'http://www.' + Memo1.Lines[i];
http := TIdHTTP.Create(nil);
try
try
http.Head(url);
code := http.ResponseCode;
except
on E: EIdSocketError do
begin
code := http.ResponseCode;
end;
on E: EIdHTTPProtocolException do
begin
code := http.ResponseCode;
end;
end;
ShowMessage(IntToStr(code));
Case code of
200:
Edit2.Text := Memo1.Lines[i] + ' website is ok';
301:
Edit2.Text := Memo1.Lines[i] + ' website has moved but works';
else
begin
Edit2.Text := 'Something is wrong with the ' + Memo1.Lines[i] + ' website';
down;
end;
end;
finally
http.Free();
end;
end;
end;
so as it is doing the http.Head(url);
how would I tell it to stop trying after 10 seconds
Simply set the timeouts after you create the HTTP component:
http := TIdHTTP.Create(nil);
http.ReadTimeout := 30000; // 30 seconds
http.ConnectTimeout := 10000; // 10 seconds
The above are timeout values that I often use. Though, you may want to use lower values and also be notified if the web sites are slow to respond.
The HTTP component will raise an exception if either timeout is exceeded.
Consider initializing code
in your for
loop to keep yourself out of trouble with future code changes, though as it stands, it's fine.
Also, consider not automatically adding www.
to each host name in your list. Instead, if your hostname requires www.
in it, add it to the list. In fact, you may wish to test both. Quite often, one simply redirects to the other, but you have the potential of losing customers if either of them is not working.
As suggested in comments, it would be ideal to run this in a separate thread than your main thread to keep your UI responsive.