fabric-synctask #1

Merged
quentinlegot merged 10 commits from fabric-synctask into master 2023-02-13 15:26:38 +01:00
4 changed files with 82 additions and 4 deletions
Showing only changes of commit 24656fa74f - Show all commits

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