Skip to content

Instantly share code, notes, and snippets.

@NotArchon
Created May 3, 2023 18:59
Show Gist options
  • Save NotArchon/c1b7570acfada5efcbcd13c66bc5724f to your computer and use it in GitHub Desktop.
Save NotArchon/c1b7570acfada5efcbcd13c66bc5724f to your computer and use it in GitHub Desktop.
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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment