1

在 Windows 中,我正在尝试编写一个 java 程序来停止 mysql 服务并更新 my.ini 文件,然后启动 mysql 服务。它可以成功运行。我可以检查使用 java 代码启动/停止的 mysql 服务的状态。如果发生任何意外情况,则指定的服务无法启动/停止,并且它也可以循环。请检查我的代码:

public void processStatusOfMySQLService() {

    String[] commandScript = { "cmd.exe", "/c", "sc", "query", "MySQL" };

    String STATE_PREFIX = "STATE              : ";



    Process process;

    try {

        process = new ProcessBuilder(commandScript).start();

        InputStream is = process.getInputStream();

        InputStreamReader isr = new InputStreamReader(is);

        BufferedReader br = new BufferedReader(isr);

        String line;

        while ((line = br.readLine()) != null) {

            // check that the temp string contains the status prefix

            int indexStatus = line.indexOf(STATE_PREFIX);

            if (indexStatus >= 0) {

                // compare status number to one of the states

                String stateStr = line.substring(

                        indexStatus + STATE_PREFIX.length(),

                        indexStatus + STATE_PREFIX.length() + 1);

                int state = Integer.parseInt(stateStr);

                switch (state) {

                case (1): 

                    // service stopped

                    break;

                case (4):

                    // service started

                    break;

                case (2):

                case (3):

                    // service pending

                    try {

                        Thread.sleep(1000);

                        processStatusOfMySQLService();

                    } catch (InterruptedException e) {

                        e.printStackTrace();

                    }

                }

            }



        }

        br.close();

        isr.close();

        is.close();

        process.destroy();



    }

如果服务无法启动/停止,我需要在特定时间后中断循环。如何设置合适的超时值???

4

0 回答 0