简体   繁体   中英

How to create a thread to run the background every 5 secs in java

I have a code to create an alarm if a value exceeds the threshold and want that code to run in the background every 5 secs.

Here is my code:

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String Name = request.getParameter("alarmName");
    String Description = request.getParameter("desc");
    String Metric = request.getParameter("name");
    String threshold = request.getParameter("threshold");
    String sign = request.getParameter("sign");

     response.setContentType("text/html");
        PrintWriter out = response.getWriter();
       // List<String> lst = new ArrayList<String>();
        System.out.println("Hello" +Name);
        System.out.println(Description);
        System.out.println(Metric);
        System.out.println(threshold);
        System.out.println(sign);


        try
    {
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","123");
        PreparedStatement ps = con.prepareStatement("Insert into alarmdetails(Name, Description, Metric, threshold,sign) values(?,?,?,?,?)");
        System.out.println(ps);
        ps.setString(1,Name);
        ps.setString(2,Description);
        ps.setString(3,Metric);
        ps.setString(4,threshold);
        ps.setString(5,sign);
        ps.executeUpdate();   

        if(Metric.equals("cpuUsage"))
        {   
            if(sign.equals("greaterthan"))
            {
                System.out.println("reached here3");
                PreparedStatement ps1 = con.prepareStatement("select CPU_USAGE from metrics WHERE CPU_USAGE > (SELECT threshold from alarmdetails WHERE Name='"+Name+"')");
                ResultSet rs1 = ps1.executeQuery();

                if(rs1.next())
                {
                    System.out.println("Alert, CPU Usage greater than threshold");
                }
                else
                {
                    System.out.println("All good");
                }
            }
        } catch (Exception e)
        {
        System.out.println(e);
        }

        String url = "Homepage.jsp";

        RequestDispatcher dispatcher = request.getRequestDispatcher(url);
        dispatcher.forward(request, response);

      }

      }

I want to run the code from if(Metric.equals(cpuUsage)).... in a thread which runs every 5 sec.

I haven't implemented thread myself before, any help would really be appreciated. Thanks.

Try using ScheduledExecutorService with the specified Delay.

ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.scheduleWithFixedDelay(new MyRunnable(), 0, 5, TimeUnit.SECONDS);

Here, the MyRunnable class would implement Runnable, and it's run method would have your processing code, without worrying about the time delays.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM