Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.demeng7215.dembot.utils;
- import com.demeng7215.dembot.files.BotStorage;
- import lombok.NonNull;
- import java.util.ArrayList;
- import java.util.Iterator;
- import java.util.List;
- import java.util.concurrent.Executors;
- import java.util.concurrent.ScheduledExecutorService;
- import java.util.concurrent.TimeUnit;
- /**
- * Checks if a temporary task has expired every 1 minute.
- * This is designed to make temporary tasks safer (eg. not banning a user forever if the bot crashes during a tempban)
- */
- public final class TimeManager {
- // List of pending temp tasks' storage file paths.
- private static List<String> tempTasks;
- public static void startTimer() {
- tempTasks = new ArrayList<>();
- ScheduledExecutorService ses = Executors.newScheduledThreadPool(1);
- Runnable checkExpired = () -> {
- Iterator<String> it = tempTasks.iterator();
- while (it.hasNext()) {
- String value = it.next();
- long expiry = BotStorage.getStorage().getLong(value);
- if (expiry <= 0 || System.currentTimeMillis() >= expiry) {
- BotStorage.getStorage().set(value, null);
- BotStorage.saveStorage();
- it.remove();
- return;
- }
- }
- };
- ses.scheduleAtFixedRate(checkExpired, 0, 1, TimeUnit.MINUTES);
- }
- /**
- * Add a temporary task to check to this util.
- *
- * @param storagePath Where the expiry time should be stored in the storage file
- * @param minutesIntoFuture Number of minutes until the temporary task expires
- */
- public static void addTempTask(@NonNull String storagePath, @NonNull int minutesIntoFuture) {
- final long expiryTime = System.currentTimeMillis() + (minutesIntoFuture * 60 * 1000);
- BotStorage.getStorage().set(storagePath, expiryTime);
- BotStorage.saveStorage();
- tempTasks.add(storagePath);
- }
- /**
- * Gets the number of minutes left in the task.
- *
- * @param storagePath Where the expiry time is stored in the storage file
- * @return 0 if the task has already expired, the number of minutes left otherwise
- */
- public static int timeLeft(@NonNull String storagePath) {
- if(!tempTasks.contains(storagePath)) return 0;
- return (int) (BotStorage.getStorage().getLong(storagePath) - System.currentTimeMillis()) / 1000 / 60;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement