gpt4 book ai didi

java - 每1小时间隔将Servlet发布请求存储在文件中一分钟

转载 作者:行者123 更新时间:2023-12-03 13:09:25 24 4
gpt4 key购买 nike

我正在尝试找到一些选项来将发布请求存储到文件中一分钟,并希望每小时重复一次。我每秒大约有3000个请求,我只想存储一分钟的请求消息,它将给我大约180000个请求进行分析。但是我想每小时对请求消息进行相同的分析。

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
ServletInputStream inputStream = request.getInputStream();
Reader reader = new InputStreamReader(inputStream);
requestMessage = gson.fromJson(reader, Request.class);

//I am trying to print requestMessage in one file for a minute at interval of 1 hour to do analysis on it
//(I am having around 3000 post requests per seconds)

} catch (Exception e) {
e.printStackTrace();
}

response.setStatus(HttpServletResponse.SC_NO_CONTENT);

}

我曾尝试在Post方法中使用以下代码,但由于每次我有新请求时都会启动新的计划,并且我将相同的代码放入init()方法中,因此它无法启动,因此无法正常工作。
service = Executors.newSingleThreadScheduledExecutor();
service.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("Starting of 1 Hour time: "+new Date());
ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();

exec.schedule(new Runnable(){
@Override
public void run(){
System.out.println("Starting of 1 minute: "+new Date());

while(requestMessage.getID().equals("123"))
{
try {
System.out.println("Printing to File: "+new Date()); Files.write(Paths.get("location/requestMessage.txt"),requestMessage, StandardOpenOption.APPEND);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}, 1, TimeUnit.MINUTES);
}
}, 0, 1, TimeUnit.HOUR);

我有点迷失在这里,寻找一些选择。
使用执行程序或线程可以做到这一点吗?如果没有,我还可以尝试其他哪些选择?

谢谢!

最佳答案

如果您想在每小时1分钟的时间内执行给定的任务,最好的办法是安排一个每隔一小时启动一次的主任务,只要不超过一分钟,它就会继续执行递归任务。

ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
// Schedule the main task to be executed every one our
service.scheduleAtFixedRate(
new Runnable() {
@Override
public void run() {
// Get the initial time
long initial = System.currentTimeMillis();
// Iterate as long as the current time - initial time is less than 60 K ms (1m)
do {
// Here is my recursive task that I want to do during 1 minute
} while ((System.currentTimeMillis() - initial) < 60_000L);
}
}, 0L, 1L, TimeUnit.HOURS
);

关于java - 每1小时间隔将Servlet发布请求存储在文件中一分钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40027885/

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