Ver Mensaje Individual
  #1  
Antiguo 04-10-2006
Avatar de seoane
[seoane] seoane is offline
Miembro Premium
 
Registrado: feb 2004
Ubicación: A Coruña, España
Posts: 3.717
Reputación: 24
seoane Va por buen camino
Esperar por un servicio

Las siguientes funciones sirven para saber si un servicio esta iniciado. Pueden resultarnos útiles, por ejemplo, si nuestra aplicación se inicia al arrancar el equipo y necesitamos esperar a que el servicio de la base de datos este iniciado.

Código Delphi [-]
uses WinSvc;

// Para comprobar si un servicio esta corriendo
function isRunning(Nombre: String): Boolean;
var
 ServiceControlManager: SC_HANDLE;
 Service: SC_HANDLE;
 ServiceStatus: SERVICE_STATUS;
begin
  Result:= FALSE;
  ServiceControlManager:= OpenSCManager(nil, nil, SC_MANAGER_CONNECT);
  if ServiceControlManager <> 0 then
  begin
    Service:= OpenService(ServiceControlManager,PChar(Nombre),GENERIC_READ);
    if Service <> 0 then
    begin
      if QueryServiceStatus(Service, ServiceStatus) then
        Result:= ServiceStatus.dwCurrentState = SERVICE_RUNNING;
      CloseServiceHandle(Service);
    end;
    CloseServiceHandle(ServiceControlManager);
  end;
end;


function Esperar(Nombre: String; TimeOut: Cardinal): Boolean;
var
  Ticks: Cardinal;
begin
  Result:= TRUE;
  Ticks:= GetTickCount;
  while not isRunning(Nombre) do
  begin
    Sleep(10);
    if GetTickCount - Ticks > TimeOut then
    begin
      Result:= FALSE;
      Exit;
    end;
  end;
end;

La primera función nos dice si un servicio esta iniciado, y la segunda espera hasta que el servicio se inicia o se cumple el tiempo de espera. Si el servicio no esta iniciado cuando se cumple el tiempo de espera la función devuelve FALSE. Un ejemplo de como usar lo anterior:

Código Delphi [-]
// Le damos 15 segundos de margen
if Esperar('NombreDelServicio',15000) then
begin
  // El servicio esta iniciado
end else
begin
  // Pasaron los 15 segundos y el servicio sigue inactivo
end;
Responder Con Cita