import org.springframework.context.annotation.Configuration;
import org.springframework.lang.NonNull;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import java.util.LinkedList;
@Configuration
@EnableScheduling
public class TaskScheduling {
private final LinkedList<Task> list = new LinkedList<>();
@Scheduled(fixedRate = 1000)
public void taskScheduling() {
long millis = System.currentTimeMillis();
for (int i = 0; i < list.size(); i++) {
Task task = list.get(i);
if (task.getUptimeMillis() < millis) {
//如果时间小于当前则是需要执行的任务
Task first = list.remove();
i--;
//如果是不可用就不执行了
if (first.isEnabled()) {
first.run();
first.setExits(false);
//如果是不再继续执行就不再添加
if (first.isLoop()) {
addTask(first, false);
}
}
}
}
}
public synchronized void addTask(Task task, boolean isFirstRun) {
//一开始执行一次
if (isFirstRun) {
task.run();
}
task.setUptimeMillis(task.getPeriod() + System.currentTimeMillis());
if (list.isEmpty()) {
task.setExits(true);
list.add(task);
return;
}
for (int i = 0; i < list.size(); i++) {
Task t = list.get(i);
if (task.isExits()) return;
if (task.getUptimeMillis() < t.getUptimeMillis()) {
task.setExits(true);
list.add(i, task);
} else {
task.setExits(true);
list.add(task);
}
}
}
//移除只是改变状态
public void remove(@NonNull String id) {
for (Task task : list) {
if (id.equals(task.getId())) {
task.setEnabled(false);
}
}
}
//不再继续执行
public void noMore(@NonNull String id) {
for (Task task : list) {
if (id.equals(task.getId())) {
task.setLoop(false);
}
}
}
}
get和set方法省略了 需要加上
public class Task implements Runnable {
private final String id;
private Runnable runnable;
private final long period;
private volatile boolean loop = true;
private volatile boolean enabled = true;
private volatile boolean exits = false;
private volatile long uptimeMillis;
public Task(String id, Runnable runnable, long period) {
this.id = id;
this.runnable = runnable;
this.period = period;
}
@Override
public void run() {
runnable.run();
}
}