我想检查一个时间链接列表,看看它们是否已经过期,而我的服务器没有从客户端获得连接,甚至每隔一两分钟检查一次。我不完全确定如何实现这一目标。我宁愿不必执行线程程序,但我知道我可能必须这样做。如果你们能给我任何反馈/建议,我将不胜感激。
这是我对一些我愚蠢地认为可行的尝试
boolean connected = false;
while(connection==null){
System.out.println("before");
connection = providerSocket.accept();
System.out.println("after");
user.checkForExpiredUsers();
}
这是它在另一个类中调用的方法。
void checkForExpiredUsers(){
String currentTime = new SimpleDateFormat("dd/MM/yy HH:mm:ss").format(new Date());
for(int i =0; i<locationLat.size();i++){
if(goodTimeDiff(currentTime,userTimeList.get(i))==false){
removeFromLists(i,locationLat,locationLong,destinationLat,destinationLong,userTimeList);
System.out.println("removed user");
System.out.println("The list of times: ");
System.out.println(userTimeList +"\n");
}
}
}
也许我可以运行一个单独的 java 程序,只需要一个 main 和 while 循环来调用这个方法? 像这样的东西:
while(true){user.checkForExpiredUsers();}
最佳答案
创建一个每分钟执行一次任务的计时器任务
public class ScheduledTask extends TimerTask {
Date now; // to display current time
// Add your task here
public void run() {
checkForExpiredUsers(); // run your code here
}
}
在主类中
Timer time = new Timer(); // Instantiate Timer Object
ScheduledTask st = new ScheduledTask();
time.schedule(st, 0, 10000); // Create Repetitively task for every 10 secs
关于java - 在等待另一个变量初始化时,如何执行执行某些操作的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29022192/