Advertisement
Guest User

Untitled

a guest
Sep 15th, 2019
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.48 KB | None | 0 0
  1. package com.demeng7215.dembot.utils;
  2.  
  3. import com.demeng7215.dembot.files.BotStorage;
  4. import lombok.NonNull;
  5.  
  6. import java.util.ArrayList;
  7. import java.util.Iterator;
  8. import java.util.List;
  9. import java.util.concurrent.Executors;
  10. import java.util.concurrent.ScheduledExecutorService;
  11. import java.util.concurrent.TimeUnit;
  12.  
  13. /**
  14. * Checks if a temporary task has expired every 1 minute.
  15. * This is designed to make temporary tasks safer (eg. not banning a user forever if the bot crashes during a tempban)
  16. */
  17. public final class TimeManager {
  18.  
  19. // List of pending temp tasks' storage file paths.
  20. private static List<String> tempTasks;
  21.  
  22. public static void startTimer() {
  23.  
  24. tempTasks = new ArrayList<>();
  25.  
  26. ScheduledExecutorService ses = Executors.newScheduledThreadPool(1);
  27.  
  28. Runnable checkExpired = () -> {
  29.  
  30. Iterator<String> it = tempTasks.iterator();
  31.  
  32. while (it.hasNext()) {
  33.  
  34. String value = it.next();
  35. long expiry = BotStorage.getStorage().getLong(value);
  36.  
  37. if (expiry <= 0 || System.currentTimeMillis() >= expiry) {
  38. BotStorage.getStorage().set(value, null);
  39. BotStorage.saveStorage();
  40. it.remove();
  41. return;
  42. }
  43. }
  44. };
  45.  
  46. ses.scheduleAtFixedRate(checkExpired, 0, 1, TimeUnit.MINUTES);
  47. }
  48.  
  49. /**
  50. * Add a temporary task to check to this util.
  51. *
  52. * @param storagePath Where the expiry time should be stored in the storage file
  53. * @param minutesIntoFuture Number of minutes until the temporary task expires
  54. */
  55. public static void addTempTask(@NonNull String storagePath, @NonNull int minutesIntoFuture) {
  56.  
  57. final long expiryTime = System.currentTimeMillis() + (minutesIntoFuture * 60 * 1000);
  58.  
  59. BotStorage.getStorage().set(storagePath, expiryTime);
  60. BotStorage.saveStorage();
  61.  
  62. tempTasks.add(storagePath);
  63. }
  64.  
  65. /**
  66. * Gets the number of minutes left in the task.
  67. *
  68. * @param storagePath Where the expiry time is stored in the storage file
  69. * @return 0 if the task has already expired, the number of minutes left otherwise
  70. */
  71. public static int timeLeft(@NonNull String storagePath) {
  72. if(!tempTasks.contains(storagePath)) return 0;
  73. return (int) (BotStorage.getStorage().getLong(storagePath) - System.currentTimeMillis()) / 1000 / 60;
  74. }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement