gpt4 book ai didi

java - 甚至可以让这个循环每次等待几秒钟吗?

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

首先,是的,我是从网络浏览器调用它的。这是一段相当长的代码,但我已尝试尽可能缩短它。

基本上,循环中的每次迭代我都需要等待 1 秒。几乎尝试了所有方法(.sleep() 等),但它似乎并没有暂停。我需要这样做的原因是因为 SimpleSocketClient 正在调用一个每秒允许的下限的套接字。

    @Override
public String execute(HttpServletRequest request, HttpServletResponse response) {
String forwardToJsp = null;
HttpSession session = request.getSession();
String allUrls = request.getParameter("domains");
ArrayList domainList = new ArrayList<String>();
Scanner sc = new Scanner(allUrls);
while (sc.hasNextLine()) {
String line = sc.nextLine();
domainList.add(line);

// process the line
}
sc.close();
String pageHtml = null;
String domain = "";
String status = "";
String registrant = "";
String dates = "";
String tag = "";
String email = "";
ArrayList domains = new ArrayList<Domain>();
Domain theDomain;

String ipAddress = request.getHeader("X-FORWARDED-FOR");
if (ipAddress == null) {
ipAddress = request.getRemoteAddr();
}

for (int i = 0; i < domainList.size(); i++) {

//NEED TO WAIT 1 SECOND HERE / ANYWHERE IN LOOP



String singleDomain = domainList.get(i).toString();



SimpleSocketClient tester = new SimpleSocketClient(singleDomain,ipAddress);
pageHtml = tester.getResult();

try {

String whoIs2 = ipAddress + " " + ipAddress + " " + singleDomain + "\r\n";

byte[] data = whoIs2.getBytes();





//details of each domain

//domain name
domain = singleDomain;

//status

status = "FTR";


//registrant

registrant = "N/A";


//dates

dates = "N/A";


//tag

tag = "N/A";


//email

email = "N/A";

}



} catch (Exception e) {
Logger.getLogger("ip is " + ipAddress + bulkWhoIsCommand.class.getName()).log(Level.SEVERE, null, e);
forwardToJsp = "index.jsp";
return forwardToJsp;
}

//single one
theDomain = new Domain(domain,status,registrant,dates,tag,email);


//now add to arrayList
domains.add(theDomain);
// try {
// Thread.sleep(230000);
// } catch (InterruptedException ex) {
// Logger.getLogger(bulkWhoIsCommand.class.getName()).log(Level.SEVERE, null, ex);
// }
// try {
// pause.poll(100 * 300, TimeUnit.MILLISECONDS);
// } catch (InterruptedException ex) {
// Logger.getLogger(bulkWhoIsCommand.class.getName()).log(Level.SEVERE, null, ex);
// }




}

编辑 - friend 建议使用 ajax 来轮询更新,但肯定有一种只使用 java 的方法。

最佳答案

你可以尝试在while循环中设置一个while循环,来暂停它。应该像这样:

 while(!done)
{
long start = System.currentTimeMillis();
while(System.currentTimeMillis() - start < 1000L){}
}

没有测试过,但方法很重要。我有一个想法将两者结合起来。因此,每次 Thread.Sleep() 崩溃时,您都必须进行循环。像这样的事情:

while(!done)
{
long start = System.currentTimeMillis();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
System.err.println(e);
}
while(System.currentTimeMillis() - start < 1000L){}
}

当 Thread.Sleep() 工作时,它只会被调用一次。否则你需要一些CPU时间。可能是cpu经济版。

关于java - 甚至可以让这个循环每次等待几秒钟吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23915838/

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