Modonomicon

Modonomicon

1M Downloads

Timer enhancement

Xaikii opened this issue ยท 1 comments

commented

This is in regards to issue #232 which I just ran into due to an outdated version.
Looking into the new solution which I thought was the issue version, I noticed that even the current solution can be improved on, as you do not need to use Threads/Timers for that.

boolean wasLoaded = false;
Set<UUID> syncRequestedPlayers = new LinkedHashSet<>();

public void updateAndSyncFor(ServerPlayer player) {
    if (BookDataManager.get().areBooksBuilt()) {
        this.getStateFor(player).update(player);
        this.saveData.setDirty();
        this.syncFor(player);
        return;
    }
    syncRequestedPlayers.add(player.getUUID());
    wasLoaded = false;
}

//Tick server tick. Source doesn't matter as long as it is the end of the tick!
public void onServerTick(ServerTickEvent event) {
    if(event.phase == Phase.START) return;//we do this at the end of a tick.
    MinecraftServer server = getServer(); //fetch the server from somewhere.
    if(server.getTickCount() % 100 != 0) return; //We only update every 5 seconds (100 ticks)
    boolean newState = BookDataManager.get().areBooksBuilt();
    if(newState != wasLoaded) { // we only check for things if the state changed for some reason.
        if(!wasLoaded && !syncRequestedPlayers.isEmpty()) { //we only process players if we have any and the state was correct.
            PlayerList list = server.getPlayerList();
            for(UUID id : syncRequestedPlayers) {
                ServerPlayer player = list.getPlayer(id);
                if(player != null) updateAndSyncFor(player);
            }
            syncRequestedPlayers.clear();
        }
        wasLoaded = newState;
    }
}
commented

That is a good point - I'll just have to check if/where fabric provides a tick event then that should be trivial to add. Thank you!