Created
May 3, 2023 18:59
-
-
Save NotArchon/c1b7570acfada5efcbcd13c66bc5724f to your computer and use it in GitHub Desktop.
Revisions
-
NotArchon created this gist
May 3, 2023 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,76 @@ package com.neox.web.pages.wrapped.hiscores; import com.mongodb.client.MongoCollection; import com.mongodb.client.model.Filters; import com.neox.web.Neox; import com.neox.web.pojo.HiscoresDoc; import io.archon.misc.StartupScript; import io.archon.misc.utils.TimeUtils; import org.bson.types.ObjectId; import java.time.DayOfWeek; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.TimeUnit; public class HiscoresPrune implements Runnable { private static final int FIND_QUERY_LIMIT = 100; private long ms; private ZonedDateTime now; private List<ObjectId> pruneIds; private final MongoCollection<HiscoresDoc> collection = Neox.getNode().getMongoDatabase() .getCollection("hiscores", HiscoresDoc.class); @Override public void run() { ms = System.currentTimeMillis(); now = ZonedDateTime.ofInstant(new Date(ms).toInstant(), ZoneId.of("UTC")); pruneIds = new ArrayList<>(); collectWeekly(); collectMonthly(); if(!pruneIds.isEmpty()) collection.deleteMany(Filters.in("_id", pruneIds)); now = null; pruneIds = null; } private void collectWeekly() { int daysPastMonday = now.getDayOfWeek().getValue() - DayOfWeek.MONDAY.getValue(); ZonedDateTime weekStart = now.truncatedTo(ChronoUnit.DAYS).minusDays(daysPastMonday); long weekStartMs = ms - TimeUtils.getMillisBetween(weekStart, now); collection.find(Filters.and( Filters.regex("key", ".*-weekly$"), Filters.lt("last_update", weekStartMs) )).limit(FIND_QUERY_LIMIT).forEach(doc -> pruneIds.add(doc._id())); } private void collectMonthly() { ZonedDateTime monthStart = now.truncatedTo(ChronoUnit.DAYS).withDayOfMonth(1); long monthStartMs = ms - TimeUtils.getMillisBetween(monthStart, now); collection.find(Filters.and( Filters.regex("key", ".*-monthly"), Filters.lt("last_update", monthStartMs) )).limit(FIND_QUERY_LIMIT).forEach(doc -> pruneIds.add(doc._id())); } @StartupScript private static void start() { Neox.getNode().scheduleAndRepeat(new HiscoresPrune(), 30000L, 30000L, TimeUnit.MILLISECONDS); } }