Created
May 3, 2023 18:58
-
-
Save NotArchon/2ed9e50802981761843b6bc3b0c9a118 to your computer and use it in GitHub Desktop.
This file contains 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 characters
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 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(100).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(100).forEach(doc -> pruneIds.add(doc._id())); | |
} | |
@StartupScript | |
private static void start() { | |
Neox.getNode().scheduleAndRepeat(new HiscoresPrune(), 30000L, 30000L, TimeUnit.MILLISECONDS); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment