gpt4 book ai didi

java - 如何在java中创建一个线程每5秒运行一次后台

转载 作者:行者123 更新时间:2023-12-01 22:20:11 25 4
gpt4 key购买 nike

我有一个代码,用于在值超过阈值时创建警报,并希望该代码每 5 秒在后台运行一次。

这是我的代码:

    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);

}

}

我想在每 5 秒运行一次的线程中运行 if(Metric.equals(cpuUsage)).... 中的代码。

我之前自己没有实现过线程,任何帮助将不胜感激。谢谢。

最佳答案

尝试使用具有指定延迟的 ScheduledExecutorService。

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

这里,MyRunnable 类将实现 Runnable,并且它的 run 方法将包含您的处理代码,而无需担心时间延迟。

关于java - 如何在java中创建一个线程每5秒运行一次后台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30018169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com