add OneTimeSyncTask and started to implement its test (not finished)

Signed-off-by: Quentin Legot <legotquentin@gmail.com>
This commit is contained in:
Quentin Legot 2023-02-12 14:51:30 +01:00
parent 9123d71a7e
commit 24656fa74f
4 changed files with 82 additions and 4 deletions

View File

@ -0,0 +1,53 @@
package fr.altarik.toolbox.task.sync;
import fr.altarik.toolbox.task.AltarikRunnable;
import fr.altarik.toolbox.task.SchedulerTaskData;
import fr.altarik.toolbox.task.TaskI;
import java.util.ArrayList;
import java.util.List;
public class OneTimeSyncTask implements TaskI, Runnable {
private final ServerTickListener listener;
private final List<SchedulerTaskData> tasks;
private OneTimeSyncTask() {
this.listener = new ServerTickListener(this);
this.tasks = new ArrayList<>(2);
}
public static TaskI initialize() {
return new OneTimeSyncTask();
}
@Override
public void addTask(AltarikRunnable function) {
addTask(function, 0);
}
public void addTask(AltarikRunnable function, int delay) {
tasks.add(new SchedulerTaskData(function, delay, 0));
}
@Override
public void run() {
List<SchedulerTaskData> removeList = new ArrayList<>(tasks.size());
for(SchedulerTaskData data : tasks) {
if(!data.getFunction().isCancelled()) {
long currentDelay = data.getCurrentDelay();
if(currentDelay != 0) {
data.setCurrentDelay(currentDelay - 1);
} else {
data.getFunction().run();
removeList.add(data);
}
} else {
removeList.add(data);
}
}
for(SchedulerTaskData toRemove : removeList) {
tasks.remove(toRemove);
}
}
}

View File

@ -9,8 +9,8 @@ import java.util.List;
public class PeriodicSyncTask implements PeriodicTaskI, Runnable {
private ServerTickListener listener;
private List<SchedulerTaskData> tasks;
private final ServerTickListener listener;
private final List<SchedulerTaskData> tasks;
private PeriodicSyncTask() {
this.listener = new ServerTickListener(this);

View File

@ -5,9 +5,9 @@ import net.minecraft.server.MinecraftServer;
public class ServerTickListener {
private final PeriodicSyncTask task;
private final Runnable task;
public ServerTickListener(PeriodicSyncTask syncTask) {
public ServerTickListener(Runnable syncTask) {
this.task = syncTask;
ServerTickEvents.START_SERVER_TICK.register(this::onServerTick);
}

View File

@ -0,0 +1,25 @@
package fr.altarik.toolbox.task.sync;
import fr.altarik.toolbox.task.AltarikRunnable;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
public class OneTimeSyncTaskTest {
@Test
void testOneTimeTask() {
OneTimeSyncTask worker = (OneTimeSyncTask) OneTimeSyncTask.initialize();
List<AtomicInteger> results = new ArrayList<>();
AtomicInteger value1 = new AtomicInteger(1);
AtomicInteger value2 = new AtomicInteger(2);
worker.addTask(new AltarikRunnable() {
@Override
public void run() {
results.add(value1);
}
});
}
}