我爱编程

2018-04-12

2018-04-12  本文已影响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();

    }

上一篇下一篇

猜你喜欢

热点阅读