unit Unit1;

interface

uses
    Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
    Dialogs, ComCtrls, ExtCtrls, StdCtrls, ActnList, ActnMan,
    IniFiles, ShellApi, CoolTrayIcon,
    Menus, OleCtrls, SHDocVw;

type
    TForm1 = class(TForm)
        PageControl1: TPageControl;
        TabSheet1: TTabSheet;
    Timer1: TTimer;
        Panel1: TPanel;
        StatusBar1: TStatusBar;
        Label1: TLabel;
        Edtime_1: TEdit;
        Label2: TLabel;
        Label3: TLabel;
        Edlast_1: TEdit;
        Label4: TLabel;
        BTN_Reset: TButton;
        TabSheet4: TTabSheet;
        CoolTrayIcon1: TCoolTrayIcon;
        PopupMenu1: TPopupMenu;
        N1: TMenuItem;
        GroupBox1: TGroupBox;
        Label5: TLabel;
        Edt_NC1: TEdit;
        Label6: TLabel;
        Label7: TLabel;
        Edt_NC2: TEdit;
        Label8: TLabel;
        Label9: TLabel;
        Edt_NC3: TEdit;
        Label10: TLabel;
        Label11: TLabel;
        Edt_NC4: TEdit;
        Label12: TLabel;
        Label13: TLabel;
        Edtuse_1: TEdit;
        Label14: TLabel;
        Label15: TLabel;
        Edt_CPU: TEdit;
        Label16: TLabel;
        Label17: TLabel;
        Edt_NC5: TEdit;
        Label18: TLabel;
        CB_IIS: TCheckBox;
        CB_MSSQL: TCheckBox;
        CB_MYSQL: TCheckBox;
        GroupBox0: TGroupBox;
        Panel2: TPanel;
        WebBrowser1: TWebBrowser;
    Label19: TLabel;
        procedure FormCreate(Sender: TObject);
        procedure Timer1Timer(Sender: TObject);
        procedure BTN_ResetClick(Sender: TObject);
        procedure FormHide(Sender: TObject);
        procedure N1Click(Sender: TObject);
        procedure CoolTrayIcon1DblClick(Sender: TObject);
        procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
        procedure FormShow(Sender: TObject);

    private
    public
        { Public declarations }
    end;

var
    myinifile: TIniFile;
    statistics: TStringList;
    TestWeb: string;
    CycleTime: Integer;
    RunningTime: Integer;
    DefaultTime: Integer;
    MinLimitMem: Integer;
    MaxLimitCPU: Integer;
    IIS_Selected: Integer;
    MSSQL_Selected: Integer;
    MYSQL_Selected: Integer;
    Form1: TForm1;
    time0: Integer;
    time1: Integer;
    time2: Integer;
    time3: Integer;

implementation

{$R *.dfm}
uses Unit2;

procedure addlog(Str: string);
var
    sFile: string;
    tFile: textFile;
begin
    sFile := ExtractFilePath(ParamStr(0)) + 'log.txt';
    AssignFile(tFile, sFile);
    if FileExists(sFile) then
        Append(tFile)
    else
        Rewrite(tFile);
    Writeln(tFile, Str);
    CloseFile(tFile);
end;

procedure readini();
begin
    myinifile := TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'config.ini');
    TestWeb := myinifile.ReadString('Option', 'TestWeb', '');
    CycleTime := myinifile.ReadInteger('Option', 'CycleTime', 0);
    RunningTime := myinifile.ReadInteger('Option', 'RunningTime', 0);
    DefaultTime := myinifile.ReadInteger('Option', 'DefaultTime', 0);
    MinLimitMem := myinifile.ReadInteger('Option', 'MinLimitMem', 0);
    MaxLimitCPU := myinifile.ReadInteger('Option', 'MaxLimitCPU', 0);
    IIS_Selected := myinifile.ReadInteger('Option', 'IIS_Selected', 0);
    MSSQL_Selected := myinifile.ReadInteger('Option', 'MSSQL_Selected', 0);
    MYSQL_Selected := myinifile.ReadInteger('Option', 'MYSQL_Selected', 0);
    Form1.Edtime_1.Text := IntToStr(RunningTime);
    Form1.Edlast_1.Text := IntToStr(MinLimitMem);
    Form1.Edtuse_1.Text := IntToStr(MaxLimitCPU);
    if IIS_Selected = 1 then
        Form1.CB_IIS.State := cbChecked;
    if MSSQL_Selected = 1 then
        Form1.CB_MSSQL.State := cbChecked;
    if MYSQL_Selected = 1 then
        Form1.CB_MYSQL.State := cbChecked;
    time0 := 0;
    time1 := RunningTime;
    Form1.WebBrowser1.Navigate(TestWeb);
end;

procedure writeini();
begin
    myinifile.WriteInteger('Option', 'RunningTime',
        StrToInt(Form1.Edtime_1.Text));
    myinifile.WriteInteger('Option', 'MinLimitMem',
        StrToInt(Form1.Edlast_1.Text));
    myinifile.WriteInteger('Option', 'MaxLimitCPU',
        StrToInt(Form1.Edtuse_1.Text));
    if Form1.CB_IIS.State = cbChecked then
        myinifile.WriteInteger('Option', 'IIS_Selected', 1)
    else
        myinifile.WriteInteger('Option', 'IIS_Selected', 0);
    if Form1.CB_MSSQL.State = cbChecked then
        myinifile.WriteInteger('Option', 'MSSQL_Selected', 1)
    else
        myinifile.WriteInteger('Option', 'MSSQL_Selected', 0);
    if Form1.CB_MYSQL.State = cbChecked then
        myinifile.WriteInteger('Option', 'MYSQL_Selected', 1)
    else
        myinifile.WriteInteger('Option', 'MYSQL_Selected', 0);
end;

function WinExecExW(cmd, workdir: PChar; visiable: Integer): DWORD;
var
    StartupInfo: TStartupInfo;
    ProcessInfo: TProcessInformation;
begin
    FillChar(StartupInfo, SizeOf(StartupInfo), #0);
    StartupInfo.cb := SizeOf(StartupInfo);
    StartupInfo.dwFlags := STARTF_USESHOWWINDOW;
    StartupInfo.wShowWindow := visiable;
    if not CreateProcess(nil, cmd, nil, nil, false,
        Create_new_console or Normal_priority_class, nil, nil,
        StartupInfo, ProcessInfo) then
        Result := 0
    else
    begin
        waitforsingleobject(processinfo.hProcess, INFINITE);
        GetExitCodeProcess(ProcessInfo.hProcess, Result);
    end;
end;


procedure TForm1.FormCreate(Sender: TObject);
var
    MutexHandle: THandle;
begin
    Timer1.Enabled := False;
    readini();
    PageControl1.Pages[0].Show;
    MutexHandle := CreateMutex(nil, true, 'WebAutoRestart');
    if (MutexHandle <> 0) and (GetLastError = ERROR_ALREADY_EXISTS) then
    begin
        CloseHandle(MutexHandle);
        Halt;
    end;
    Application.Initialize;
    Application.Run;
    CoolTrayIcon1.IconVisible := true;
    form1.WindowState := wsMinimized;
end;

procedure TForm1.Timer1Timer(Sender: TObject);
var
    MemInfo: MEMORYSTATUS;
begin
    if (time0 = 0) then
    begin
        WebBrowser1.Refresh;
        time0 := CycleTime;
    end
    else
        time0 := time0 - 1;
    CollectCPUData;
    GlobalMemoryStatus(MemInfo);
    Edt_NC1.Text := IntToStr(MemInfo.dwTotalPhys div (1024 * 1024));
    Edt_NC2.Text := IntToStr(MemInfo.dwAvailPhys div (1024 * 1024));
    Edt_NC3.Text := IntToStr(MemInfo.dwTotalVirtual div (1024 * 1024));
    Edt_NC4.Text := IntToStr(MemInfo.dwAvailVirtual div (1024 * 1024));
    Edt_NC5.Text := IntToStr(MemInfo.dwMemoryLoad);
    Edt_CPU.Text := IntToStr(Round(GetCPUUsage(GetCPUCount - 1) * 100));

    if (MinLimitMem > StrToInt(Edt_NC2.Text)) or
        (MaxLimitCPU < StrToInt(Edt_CPU.Text)) then
    begin
        time1 := time1 - 1;
        if Time1 > 0 then
            StatusBar1.Panels[0].Text :=
                '还有' + IntToStr(time1) + '秒重启WEB服务'
        else if Time1 = 0 then
        begin
            StatusBar1.Panels[0].Text := '正在重启WEB服务';
            addlog('CPU使用：' + Edt_CPU.Text + '%    内存剩余：' + Edt_NC2.Text + 'M');
        end
        else
        begin
            WinExecExW('iisreset /stop', '', sw_hide);
            if (MSSQL_Selected = 1) and (MinLimitMem > StrToInt(Edt_NC2.Text)) then
            begin
                WinExecExW('net stop mssqlserver', '', sw_hide);
                WinExecExW('net start mssqlserver', '', sw_hide);
                addlog('[' + DateToStr(Now) + ' ' + TimeToStr(Now)
                    + '] [MSSQL]:成功重启');
            end;
            if (MYSQL_Selected = 1) and (MinLimitMem > StrToInt(Edt_NC2.Text)) then
            begin
                WinExecExW('net stop mysql', '', sw_hide);
                WinExecExW('net start mysql', '', sw_hide);
                addlog('[' + DateToStr(Now) + ' ' + TimeToStr(Now)
                    + '] [MYSQL]:成功重启');
            end;
            WinExecExW('iisreset /start', '', sw_hide);
            addlog('[' + DateToStr(Now) + ' ' + TimeToStr(Now) +
                '] [IIS]:成功重启');
            addlog('-------------------------------------------------------------');
            time1 := RunningTime;
        end;
    end
    else
    begin
        time1 := RunningTime;
        StatusBar1.Panels[0].Text := '计算机运行正常';
    end;
end;

procedure TForm1.BTN_ResetClick(Sender: TObject);
begin
    myinifile := TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'config.ini');
    if (StrToInt(Edtime_1.Text) < 10) or
        (StrToInt(Edtime_1.Text) > 240) then
        StatusBar1.Panels[0].Text := '请输入10-240的整数'
    else if (StrToInt(Edlast_1.Text) < (StrToInt(Edt_NC1.Text) div 10)) or
        (StrToInt(Edlast_1.Text) > (StrToInt(Edt_NC1.Text) div 2)) then
        StatusBar1.Panels[0].Text := '请输入' +
            IntToStr(StrToInt(Edt_NC1.Text) div 10) + '-' +
            IntToStr(StrToInt(Edt_NC1.Text) div 2) + '的整数'
    else if (StrToInt(Edtuse_1.Text) < 50) or
        (StrToInt(Edtuse_1.Text) > 100) then
        StatusBar1.Panels[0].Text := '请输入50-100的整数'
    else
        writeini();
    readini();
end;


procedure TForm1.FormHide(Sender: TObject);
begin
    CoolTrayIcon1.HideMainForm;
    //CoolTrayIcon1.IconVisible := true;
end;

procedure TForm1.N1Click(Sender: TObject);
begin
    Close();
end;

procedure TForm1.CoolTrayIcon1DblClick(Sender: TObject);
begin
    CoolTrayIcon1.showMainForm;
    //CoolTrayIcon1.IconVisible := false;
end;

procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
    {if Application.MessageBox('确信要关闭？', '关闭系统',
        MB_ICONQUESTION + MB_YESNO) = idNo then
        CanClose := false
    else  }
        CanClose := true;
end;

procedure TForm1.FormShow(Sender: TObject);
begin
    Timer1.Enabled := True;
    //PageControl1.Pages[0].Show;
end;

end.

