java代码5秒运行一次_如何在java中創建一個每5秒運行一次后台的線程

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方法將具有您的處理代碼,而不必擔心時間延遲。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值