0

我正在开发一个将安排任务的课程,如果该任务花费了 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");

    }
}
4

1 回答 1

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();
于 2012-12-22T08:03:55.880 回答