2018-04-12

作者: 天晴_听云 | 来源:发表于2018-04-12 18:09 被阅读0次

    关于心跳机制的代码

    // 定时输出心跳文件,用于运维检测进程是否还活着

     final String heartbeatFile = System.getProperty("heartbeat.file");

    final AtomicBoolean shutdown =new AtomicBoolean(false);

    if(heartbeatFile !=null && heartbeatFile.length() >0) {

    String heartbeatInterval = System.getProperty("heartbeat.interval.ms");

    final long heartbeatIntervalInMillis = (heartbeatInterval ==null || heartbeatInterval.length() ==0 ?1000L : Long.parseLong(heartbeatInterval));

    new Thread(new Runnable() {

            public void run() {

                    for( ; !shutdown.get() ; ) {

                    FileOutputStream hearbeatOut =null;

            try {

                    hearbeatOut =new FileOutputStream(heartbeatFile);

                    hearbeatOut.write(String.valueOf(System.currentTimeMillis()).getBytes("ISO_8859_1"));

                    hearbeatOut.flush();

             }catch(IOException ex) {

                    System.out.println("failed to write heartbeat file: " +heartbeatFile +": " + ex.getMessage());

                    ex.printStackTrace();

               }finally {

                    if(hearbeatOut !=null) {

                    try {

                        hearbeatOut.close();

                    }catch (IOException e) {

                        System.out.println("failed to close heartbeat file: " +heartbeatFile);

                        e.printStackTrace();

                        }

                    }

                }

                    try {

                        Thread.sleep(heartbeatIntervalInMillis);

                    }catch (InterruptedException e) {

                        e.printStackTrace();

                    }

                }

            }

            },"thread-bootstrap-heartbeat").start();

        }

    相关文章

      网友评论

        本文标题:2018-04-12

        本文链接:https://www.haomeiwen.com/subject/eqefkftx.html