Advertisement
Macari

Delphi - ServiceApp - Thread

Dec 13th, 2016
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Delphi 7.45 KB | None | 0 0
  1.  unit unThreadCrons;
  2.  
  3. interface
  4.  
  5. uses Classes {$IFDEF MSWINDOWS}, Windows {$ENDIF}, Dialogs, SysUtils, ShellApi,ZAbstractRODataset, ZAbstractDataset, ZDataset,
  6.   ZAbstractConnection, ZConnection, BotLibrary;
  7.  
  8. type
  9.   ThreadCrons = class(TThread)
  10.   protected
  11.  
  12.   private
  13.     FComando    : String;
  14.     FLocal      : String;
  15.     FMsgKill    : String;
  16.     FAdendo     : String;
  17.     FPID        : Cardinal;
  18.     FDisparador : integer;
  19.     FCron       : integer;
  20.     FForcar     : boolean;
  21.     Interrupcao : Cardinal;
  22.     ProcessHandle : Cardinal;
  23.   //  ExitCode    : Cardinal;
  24.   //  StartupInfo : TStartupInfo;
  25.   //  ProcessInfo : TProcessInformation;
  26.     FCountConcorrencia : Integer;
  27.     Query : TZQuery;
  28.     Conexao     : TZConnection;
  29.     Mensagem : String;
  30.     FConcorrencia : Boolean;
  31.     TerminoExterno,FProcessoVivo : boolean;
  32.     FSituacao: integer;
  33.   public
  34.     procedure Execute; override;
  35.     property Cron : integer read FCron write FCron;
  36.     property Comando : string read FComando write FComando;
  37.     property Local : string read FLocal write FLocal;
  38.     property PID : Cardinal read FPID Write FPID;
  39.     property Disparador : integer read FDisparador write FDisparador;
  40.     property Situacao : integer read FSituacao write FSituacao;
  41.     property ProcessoVivo : boolean read FProcessoVivo write FProcessoVivo;
  42.     property Forcar : boolean read FForcar write FForcar;
  43.     property MsgKill : String read FMsgKill write FMsgKill ;
  44.     property Concorrencia : Boolean read FConcorrencia write FConcorrencia;
  45.     property CountConcorrencia : Integer read FCountConcorrencia write FCountConcorrencia;
  46.     constructor Create (VForcar : boolean; VPID : Cardinal; VCron, VDisparador : integer ; VInterrupcao : Cardinal); overload;
  47.   {  destructor Destroy; override;}
  48.     procedure ProcessTerminate;
  49.      end;
  50.  
  51. implementation
  52.  
  53. { ThreadCrons }
  54.  
  55. constructor ThreadCrons.Create(VForcar : Boolean; VPID : Cardinal ; VCron, VDisparador : integer ; VInterrupcao : Cardinal);
  56. begin
  57.   inherited Create(True);
  58.   FreeOnTerminate := False;
  59.  
  60.   Disparador  := VDisparador;
  61.   PID         := VPID;
  62.   Interrupcao := VInterrupcao;
  63.   Cron        := VCron;
  64.   Forcar      := VForcar;
  65.   TerminoExterno := false;
  66.   Concorrencia   := false;
  67.   MsgKill := '';
  68.  
  69.   Situacao := 0;
  70.   CountConcorrencia := 0;
  71.  
  72.   try
  73.     Conexao := TZConnection.Create(nil);
  74.  
  75.     Conexao.DataBase := 'WebBot';
  76.     Conexao.HostName := 'webglobaldb1.com.br';
  77.     Conexao.LoginPrompt := false;
  78.     Conexao.Password := 'botcron123';
  79.     Conexao.Protocol := 'postgresql-9';
  80.     Conexao.User := 'BotCron';
  81.     Conexao.Connect;
  82.  
  83.     Query := TZQuery.Create(nil);
  84.     Query.Connection := Conexao;
  85.  
  86.   except
  87.     on e: exception do
  88.       LogErro('Erro ao Conectar a base de dados - Thread Crons','',e.Message,'BotCronThread');
  89.   end;
  90. end;
  91.  
  92. procedure ThreadCrons.Execute;
  93. var IDLog : Integer;
  94.     Retorno : DWORD;
  95.  
  96.   procedure WaitCron;
  97.   begin
  98.  
  99.     GravaMensagem(Disparador,'Executando');
  100.  
  101.     //StrPCopy(zAppName, FileName);
  102.     //FillChar(StartupInfo, Sizeof(StartupInfo), #0);
  103.     //StartupInfo.cb := Sizeof(StartupInfo);
  104.     //if CreateProcessW(nil, zAppName,nil,nil, false,0, nil, nil, StartupInfo, ProcessInfo) then
  105.     //begin
  106.       ProcessoVivo := true;
  107.       try
  108.         Query.SQL.Clear;
  109.         Query.SQL.Add('insert into log_crons(cron,inicio,disparador,PID) values (:pCron,clock_timestamp(),:pDisparador,:ppid) returning ID');
  110.         Query.ParamByName('pCron').AsInteger       := Cron;
  111.         Query.ParamByName('pdisparador').AsInteger := Disparador;
  112.         Query.ParamByName('ppid').AsInteger        := PID;
  113.         Query.Open;
  114.  
  115.         IDLog := Query.FieldByName('id').AsInteger;
  116.  
  117.         Query.SQL.Clear;
  118.         Query.SQL.Add('update crons_disparadores set PID = :pPID where disparador = :pDisparador');
  119.         Query.ParamByName('pPID').AsInteger        := PID;
  120.         Query.ParamByName('pDisparador').AsInteger := Disparador;
  121.         Query.ExecSQL;
  122.       except
  123.         on e: exception do
  124.         begin
  125.           LogErro('Erro ao gravar Log Cron! ID: ' + IntToStr(Disparador), 'Serviço Thread Crons', e.Message, 'BotCronThread');
  126.         end;
  127.       end;
  128.  
  129.       FAdendo := '';
  130.  
  131.       ProcessHandle := OpenProcess($00100000, false, PID);
  132.  
  133.       Retorno := WaitforSingleObject(ProcessHandle, Interrupcao);
  134.  
  135.       if Retorno = WAIT_TIMEOUT then
  136.       begin
  137.         FAdendo := 'WAIT_TIMEOUT';
  138.  
  139.         MsgKill := 'Parado Por Tempo de Interrupção';
  140.  
  141.         if Concorrencia then
  142.           MsgKill := MsgKill + ' - Extendida Execução ('+InttoStr(CountConcorrencia)+')';
  143.  
  144.         ProcessTerminate;
  145.       end
  146.       else
  147.       begin
  148.         case Retorno of
  149.           WAIT_FAILED    : FAdendo := 'WAIT_FAILED';
  150.           WAIT_OBJECT_0  : FAdendo := 'WAIT_OBJECT_0';
  151.           WAIT_ABANDONED : FAdendo := 'WAIT_ABANDONED';
  152.         end;
  153.  
  154.         if not TerminoExterno then
  155.         begin
  156.           if Forcar then
  157.             Mensagem := 'Execução Forçada Pelo Usuário.'
  158.           else
  159.           begin
  160.             Mensagem := 'Executado Com Sucesso' ;
  161.             if Concorrencia then
  162.               Mensagem := Mensagem + ' - Extendida Execução ('+InttoStr(CountConcorrencia)+')';
  163.           end;
  164.  
  165.           GravaMensagem(Disparador,Mensagem);
  166.  
  167.           //CloseHandle(ProcessInfo.hThread);
  168.           CloseHandle(ProcessHandle);
  169.         end;
  170.       end;
  171.  
  172.       if Retorno = WAIT_FAILED then
  173.         LogErro('Erro CreateProcess Thread Crons - Disparador : ' +inttostr(Disparador) + ' - PID : ' + IntToStr(PID) ,'CreateProcess','Interrupção : ' +IntToStr(Interrupcao) + ' - Last Error : ' + IntToStr(HResultFromWin32(GetLastError)) ,'BotCronThread');
  174.  
  175.       // atualiza banco de dados
  176.       try
  177.         if (MsgKill <> '') then
  178.           Mensagem := MsgKill;
  179.  
  180.         Query.SQL.Clear;
  181.         Query.SQL.Add('update log_crons set fim = clock_timestamp(), status_process =:pStatusProcess, status = :pstatus where id = :pId ');
  182.         Query.ParamByName('pId').AsInteger           := IDLog;
  183.         Query.ParamByName('pstatus').AsString        := Mensagem;
  184.         Query.ParamByName('pStatusProcess').AsString := FAdendo;
  185.         Query.ExecSQL;
  186.       except
  187.         on e: exception do
  188.         begin
  189.            LogErro('Erro ao gravar Log Cron - ID: ' + IntToStr(Disparador), 'Serviço Thread Crons', e.Message, 'BotCronThread');
  190.         end;
  191.       end;
  192.     //end;
  193.  
  194.     ProcessoVivo := false;
  195.   end;
  196.  
  197. begin
  198.   try
  199.     if Conexao.PingServer then
  200.       WaitCron;
  201.   except
  202.     on e: exception do
  203.     begin
  204.        LogErro('Erro ao executar Cron Thread! ID: ' + IntToStr(Disparador), 'Serviço Thread Crons', e.Message, 'BotCronThread');
  205.     end;
  206.   end;
  207.  
  208.   Query.Free;
  209.   Conexao.Free;
  210.  
  211.   Situacao := 1;
  212. end;
  213.  
  214. procedure ThreadCrons.ProcessTerminate();
  215. begin
  216.   try
  217.     if ProcessoVivo then
  218.     begin
  219.       TerminoExterno := true;
  220.  
  221.       GravaMensagem(Disparador, FMsgKill);
  222.  
  223.    //   GetExitCodeProcess(ProcessInfo.hProcess, ExitCode);
  224.  
  225.    //   TerminateProcess(ProcessInfo.hProcess, ExitCode);
  226.  
  227.     //  CloseHandle(ProcessInfo.hThread);
  228.       CloseHandle(ProcessHandle);
  229.       ProcessHandle := OpenProcess(PROCESS_TERMINATE, false, PID);
  230.       TerminateProcess(ProcessHandle, ExitCode);
  231.       CloseHandle(ProcessHandle);
  232.  
  233.       ProcessoVivo := false;
  234.     end;
  235.   except
  236.     on e : exception do
  237.       LogErro('Erro ao Matar Processo - PID :'+inttostr(PID)+ ' Disparador : '  +IntToStr(Disparador),'',e.Message,'BotCronThread');
  238.   end;
  239. end;
  240.  
  241. end.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement