如何在完成迭代arraylist Java后停止Timer

时间:2016-04-08 23:36:51

标签: java arraylist timer

我有这个计时器方法:

public void setTimer(int seconds, String userName, String content) {
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            setTweet(userName, content);
            System.out.println("tweet posteado cada 5 segs");
        }
    }, 0, (seconds*1000));       
}  

变量"内容"由arraylist定义。如何启动计时器,通过arraylist迭代并在计时器结束时停止计时器?

编辑:添加了arraylist:

public ArrayList<String> readSelectedExcel(File path){
    ArrayList<String> tweetsArray = new ArrayList<>();
    try{
        FileInputStream fileInputStream = new FileInputStream(path);
        XSSFWorkbook wb = new XSSFWorkbook(fileInputStream);
        XSSFSheet sheet = wb.getSheetAt(0);
        sheet = wb.getSheetAt(0);
        for (Row myrow : sheet) {
            for (Cell mycell : myrow) {
                tweetsArray.add(mycell.getStringCellValue());
            }
        }
    }catch (FileNotFoundException te) {
        te.printStackTrace();
        System.out.println("Accounts.xlsx Not Found");
    } catch (IOException e) {
        e.printStackTrace();
    }  

    return tweetsArray;
}

2 个答案:

答案 0 :(得分:1)

您可以使用schedule(TimerTask task, long delay)代替scheduleAtFixedRate(TimerTask task, long delay, long period)

以下是一个例子:

int seconds = 1;
for(int i = 0; i < list.size(); i++){
    setTimer(seconds * i, userName,list.get(i));
}

public void setTimer(int seconds, final String userName, final String content) {
         Timer timer = new Timer();
         timer.schedule(new TimerTask() {
             @Override
             public void run() {
                 setTweet(userName, content);
                 System.out.println("tweet posteado cada 5 segs");
             }
         }, (seconds*1000));       
}

答案 1 :(得分:0)

如果您保留对计时器对象的引用。然后检查您的ararylist是否为空,然后调用timer.cancel()https://docs.oracle.com/javase/7/docs/api/java/util/Timer.html#cancel()