Foros Club Delphi

Foros Club Delphi (https://www.clubdelphi.com/foros/index.php)
-   Trucos (https://www.clubdelphi.com/foros/forumdisplay.php?f=52)
-   -   Esperar por un servicio (https://www.clubdelphi.com/foros/showthread.php?t=80765)

seoane 04-10-2006 13:50:38

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;


La franja horaria es GMT +2. Ahora son las 09:44:51.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi