修改定时器

This commit is contained in:
wind 2023-04-08 20:11:35 +08:00
parent 84a318fdf3
commit 8bb7d883b5

View File

@ -4,43 +4,20 @@ import java.util.*;
/** /**
* <p>类名: DelayedTime * <p>类名: DelayedTime
* <p>说明 定时器队列 * <p>说明 定时器
*
* @author :Wind * @author :Wind
* 2023/3/25 21:22 * 2023/3/25 21:22
**/ **/
public class DelayedTime { public class DelayedTime {
private final List<Task> queue = Collections.synchronizedList(new ArrayList<>()); private final Timer timer = new Timer(true);
public DelayedTime() {
Timer timer = new Timer(true);
Thread t = new Thread(() -> {
while (true) try {
if (queue.size() == 0){
continue;
}
Task take = queue.remove(0);
timer.schedule(take.getRunnable(), take.getTime());
} catch (Exception e) {
e.printStackTrace();
}
});
t.start();
}
/** /**
* 延迟队列添加新任务 * 延迟队列添加新任务
*/ */
public void schedule(TimerTask task, long delay) { public void schedule(TimerTask task, long delay) {
try { timer.schedule(task,delay);
Task tasks = new Task();
tasks.setTime(delay);
tasks.setRunnable(task);
queue.add(tasks);
} catch (Exception e) {
throw new RuntimeException(e);
}
} }
} }