我正在做一个程序,登录到一个网站。它得到一些值,然后每135分钟左右对网站进行一定的点击。值,"obtained_value“是从该网站读取的,该值通过每次单击该程序所产生的某个值而减少。我想要运行程序,直到得到的值小于10。一旦发生这种情况,我想暂停程序,直到达到目标时间,并重新启动点击周期。每次达到目标时间我都想这么做。我在下面的代码中实现了这个逻辑,但是在达到目标时间之后,我的代码仍然处于休眠状态,而不是重新启动循环。我怎么才能解决这个问题?
while (true) {
var remainder = driver.findElement(By.xpath(
"/html/body/uni-app/uni-page/uni-page-wrapper/uni-page-body/uni-view/uni-view[3]/uni-view[2]/uni-view[2]")).getText();
var remaining = Double.parseDouble(remainder);
var last_time = driver.findElement(By.xpath(
"/html/body/uni-app/uni-page/uni-page-wrapper/uni-page-body/uni-view/uni-view[5]/uni-view[3]/uni-view[1]")).getText();
Calendar date = Calendar.getInstance();
date.setTime(new SimpleDateFormat("MM-dd HH:mm", Locale.ENGLISH).parse(last_time)); // Parse into Date object
date.set(Calendar.YEAR, 2022);
var obtained_value = date.getTime().getTime();
long current_time = Calendar.getInstance().getTimeInMillis(); // Get time now
long target_time = obtained_value + 7920000;
long millis = target_time - System.currentTimeMillis();
if (millis <= 0) {
if (remaining > 5) {
driver.findElement(By.className("orderBtn")).click();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Thread.sleep(6000);
driver.findElement(By.xpath("/html/body/uni-app/uni-page/uni-page-wrapper/uni-page-body/uni-view/uni-view[7]/uni-view/uni-view/uni-view[6]/uni-button[2]")).click();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Thread.sleep(6000);
driver.findElement(By.xpath("/html/body/uni-app/uni-page/uni-page-wrapper/uni-page-body/uni-view/uni-view[8]/uni-view/uni-view/uni-button")).click();
}
}
try {
if(millis > 0)
Thread.sleep(millis);
else
continue;
} catch (InterruptedException e) {
throw new RuntimeException(e.getMessage(), e);
}
}由于Thread.sleep不接受负值,所以代码在到达指定时间后中断是有意义的,但我目前不知道如何避免这个错误。如何在每次到达Thread.sleep(millis)时恢复循环?在这个时刻,即使在达到目标时间之后,程序仍然保持睡眠状态。
发布于 2022-05-12 16:19:37
您的问题非常类似于这个问题:您能使用无限循环继续使用java运行程序吗?。主要问题是安排重新发生的任务,您应该使用可以从ScheduledExecutorService方法获得的Executors.newScheduledThreadPool(int corePoolSize)。一旦您注意到所获得的值小于10,您应该关闭您的ScheduledExecutorService,并创建一个新的wich,您可以将您的任务安排在指定的时间间隔内开始。
https://stackoverflow.com/questions/72218659
复制相似问题