我正在开发一个将安排任务的课程,如果该任务花费超过2分钟,那么我将显示一条消息,表明任务已经完成,因为任务花了2分钟以上,并且任务完成在2分钟之内或之前,我将在2分钟之前显示任务完成的消息,现在挑战是我想要一个虚拟任务,先说一个循环来测试它,请指教如何实现,下面是代码到目前为止我已经尝试过了..
import java.util.Timer;
import java.util.TimerTask;
public class Reminder {
Timer timer;
public Reminder(int seconds) {
timer = new Timer();
timer.schedule(new RemindTask(), seconds*1000);
}
class RemindTask extends TimerTask { // Nested Class
public void run() {
//hOW TO SET THE any kind of task which takes more than 5 minutes any loop or any sort of thing
// If elapsed time is > 50 minutes, something is not right
System.out.format("Time's up since it takes more than 5 minutes....!%n");
timer.cancel(); //Terminate the timer thread
}
}
public static void main(String args[]) {
new Reminder(5);
System.out.format("Task scheduled.%n");
}
}
答案 0 :(得分:1)
这将帮助您入门:
public abstract class LimitedTask {
private final long timeOut;
private final Timer timer;
private final AtomicBoolean flag;
protected LimitedTask(long timeOut) {
this.timeOut = timeOut;
this.timer = new Timer("Limiter",true);
this.flag = new AtomicBoolean(false);
}
public void execute(){
//---worker--
final Thread runner = new Thread(new Runnable() {
@Override
public void run() {
try{
doTaskWork();
}catch (Exception e){
e.printStackTrace();
}finally {
if(flag.compareAndSet(false,true)){
timer.cancel();
onFinish(false);
}
}
}
},"Runner");
runner.setDaemon(true);
runner.start();
//--timer--
this.timer.schedule(new TimerTask() {
@Override
public void run() {
runner.interrupt();
if(flag.compareAndSet(false,true)){
onFinish(true);
}
}
},this.timeOut);
}
public abstract void onFinish(boolean timedOut);
public abstract void doTaskWork() throws Exception;
}
测试实施:
public class TestTask extends LimitedTask {
public TestTask() {
super(10000);
}
@Override
public void onFinish(boolean timedOut) {
System.out.println(timedOut ? "Task timed out" : "Task completed");
}
@Override
public void doTaskWork() throws Exception {
for (int i = 0; i <100 ; i++){
Thread.sleep(1000);
}
}
}
执行命令
TestTask t = new TestTask();
t.execute();