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.
我有一個代碼來創建一個警報,如果一個值超過閾值,並希望該代碼每5秒在后台運行。
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 lst = new ArrayList();
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.
我想從if(Metric.equals(cpuUsage))....運行代碼,每隔5秒運行一次。
I haven't implemented thread myself before, any help would really be appreciated. Thanks.
我之前沒有自己實現過線程,任何幫助都會非常感激。謝謝。
1 个解决方案
#1
Try using ScheduledExecutorService with the specified Delay.
嘗試使用具有指定延遲的ScheduledExecutorService。
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.
在這里,MyRunnable類將實現Runnable,它的run方法將具有您的處理代碼,而不必擔心時間延遲。