2017-06-01 24 views
0

我已经掌握了Timer和TimerTask如何在Java中工作的基础知识。我有一种情况,我需要产生一个定期运行的任务,以固定的时间间隔从数据库中检索一些数据。它需要基于检索到的数据的值终止(数据本身正在被其他进程更新)Java使用来自任务本身的数据终止一个时间任务

这是我到目前为止所提出的。

public class MyTimerTask extends TimerTask { 

    private int count = 0; 
    @Override 
    public void run() { 
     count++; 
     System.out.println(" Print a line" + new java.util.Date() + count); 
    } 

    public int getCount() { 
     return count; 
    } 
} 

和一个类似的主要方法。现在我已经平凡地使用了15秒的睡眠时间来控制timerTask运行的时间。

public class ClassWithMain { 
public static void main(String[] args) { 
    System.out.println("Main started at " + new java.util.Date()); 
    MyTimerTask timerTask = new MyTimerTask(); 
    Timer timer = new Timer(true); 
    timer.scheduleAtFixedRate(timerTask, 0, 5*10*100); 

    try { 
     Thread.sleep(15000); 
    } catch (InterruptedException e) { 
     e.printStackTrace(); 
    } 
    System.out.println("Main done"+ new java.util.Date()); 

} 

对于数据库服务调用等,MyTimerTask类将变得更加复杂。

我希望能够做的是,在主类中,询问timerTask返回的值,以指示何时调用timer.cancel()并终止进程。现在,如果我尝试使用MyTimerTask的count属性,它不起作用。所以当我尝试在ClassWithMain中添加这些行时

if (timerTask.getCount() == 5){ 
    timer.cancel(); 
} 

它并没有停止这个过程。

因此,我想就我如何能够完成我想要做的事情发表任何指示。

+0

为什么你认为timerTask.getCount()将线程睡眠后是5。它最有可能是3,因为在15000工厂之后它增加了3次。如果当count为5时需要取消,则将该逻辑正确放入run方法中,并将Timer传递给MyTimerTask,以便run方法可以访问它。 – tsolakp

+0

这似乎也是一种有效的方法......我从来没有想过要将计时器传递给run()方法! – ChuckLeviton

回答

1

private volatile int count = 0;最好使用'volatile'。
试试这个在ClassWithMain:

for(;;) { 
    if (timerTask.getCount() == 5) { 
    timer.cancel(); 
    break; 
    } else{ 
    Thread.yield(); 
    } 
}