gpt4 book ai didi

java - 关于计时器实用程序

转载 作者:行者123 更新时间:2023-12-01 14:58:39 26 4
gpt4 key购买 nike

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

}
}

最佳答案

这将帮助您开始:

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();

关于java - 关于计时器实用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14000787/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com