Skip to content

Commit

Permalink
Created TaskScheduler to be able to cancel existing events for a mess…
Browse files Browse the repository at this point in the history
…age when overwriting paginator;

Changed EventHandler methods to accept the ID directly, instead of a message.
  • Loading branch information
ygimenez committed Oct 18, 2024
1 parent 6169161 commit 7a0d0ab
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 23 deletions.
10 changes: 4 additions & 6 deletions src/main/java/com/github/ygimenez/listener/EventHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,12 @@ public EventHandler() {
* Adds an event to the handler, which will be executed whenever a button with the same
* ID is pressed.
*
* @param msg The {@link Message} to hold the event.
* @param id The event ID.
* @param act The action to be executed when the button is pressed.
* @return An {@link ActionReference} pointing to this event. This is useful if you need to track whether an event
* is still being processed or was already removed (i.e. garbage collected).
*/
public ActionReference addEvent(@NotNull Message msg, @NotNull ThrowingBiConsumer<User, PaginationEventWrapper> act) {
String id = getEventId(msg);
public ActionReference addEvent(@NotNull String id, @NotNull ThrowingBiConsumer<User, PaginationEventWrapper> act) {
Pages.getPaginator().log(PUtilsConfig.LogLevel.LEVEL_3, "Added event with ID " + id + " and Consumer hash " + Integer.toHexString(act.hashCode()));
events.put(id, act);

Expand All @@ -61,10 +60,9 @@ public ActionReference addEvent(@NotNull Message msg, @NotNull ThrowingBiConsume
/**
* Removes an event from the handler.
*
* @param msg The {@link Message} which had attached events.
* @param id The event ID.
*/
public void removeEvent(@NotNull Message msg) {
String id = getEventId(msg);
public void removeEvent(@NotNull String id) {
Pages.getPaginator().log(PUtilsConfig.LogLevel.LEVEL_3, "Removed event with ID " + id);
events.remove(id);
dropdownValues.remove(id);
Expand Down
38 changes: 21 additions & 17 deletions src/main/java/com/github/ygimenez/method/Pages.java
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
* to {@link #paginate}, {@link #categorize}, {@link #buttonize} and {@link #lazyPaginate}.
*/
public abstract class Pages {
private static final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();
private static final TaskScheduler scheduler = new TaskScheduler();
private static final EventHandler handler = new EventHandler();
private static Paginator paginator;

Expand Down Expand Up @@ -573,7 +573,8 @@ public static ActionReference paginate(@NotNull Message msg, @NotNull PaginateHe
addReactions(msg, helper.getSkipAmount() > 1, helper.isFastForward());
}

return handler.addEvent(msg, new ThrowingBiConsumer<>() {
String evt = handler.getEventId(msg);
return handler.addEvent(evt, new ThrowingBiConsumer<>() {
private final int maxP = pgs.size() - 1;
private int p = 0;
private ScheduledFuture<?> timeout;
Expand All @@ -582,7 +583,7 @@ public static ActionReference paginate(@NotNull Message msg, @NotNull PaginateHe
timeout.cancel(true);
}

handler.removeEvent(msg);
handler.removeEvent(evt);
if (paginator.isDeleteOnCancel()) msg.delete().submit();
};

Expand All @@ -591,7 +592,7 @@ public static ActionReference paginate(@NotNull Message msg, @NotNull PaginateHe

{
if (helper.getTimeout() > 0) {
timeout = worker.schedule(() -> finalizeEvent(msg, success), helper.getTimeout(), TimeUnit.MILLISECONDS);
timeout = scheduler.schedule(evt, () -> finalizeEvent(msg, success), helper.getTimeout(), TimeUnit.MILLISECONDS);
}
}

Expand Down Expand Up @@ -680,7 +681,7 @@ public void acceptThrows(@NotNull User u, @NotNull PaginationEventWrapper wrappe
timeout.cancel(true);
}
if (helper.getTimeout() > 0) {
timeout = worker.schedule(() -> finalizeEvent(msg, success), helper.getTimeout(), TimeUnit.MILLISECONDS);
timeout = scheduler.schedule(evt, () -> finalizeEvent(msg, success), helper.getTimeout(), TimeUnit.MILLISECONDS);
}

if (wrapper.isFromGuild() && wrapper.getSource() instanceof MessageReactionAddEvent && paginator.isRemoveOnReact()) {
Expand Down Expand Up @@ -849,21 +850,22 @@ public static ActionReference categorize(@NotNull Message msg, @NotNull Categori
msg.addReaction(paginator.getEmoji(CANCEL)).submit();
}

return handler.addEvent(msg, new ThrowingBiConsumer<>() {
String evt = handler.getEventId(msg);
return handler.addEvent(evt, new ThrowingBiConsumer<>() {
private ButtonId<?> currCat = null;
private ScheduledFuture<?> timeout;
private final Consumer<Void> success = s -> {
if (timeout != null) {
timeout.cancel(true);
}

handler.removeEvent(msg);
handler.removeEvent(evt);
if (paginator.isDeleteOnCancel()) msg.delete().submit();
};

{
if (helper.getTimeout() > 0) {
timeout = worker.schedule(() -> finalizeEvent(msg, success), helper.getTimeout(), TimeUnit.MILLISECONDS);
timeout = scheduler.schedule(evt, () -> finalizeEvent(msg, success), helper.getTimeout(), TimeUnit.MILLISECONDS);
}
}

Expand Down Expand Up @@ -916,7 +918,7 @@ public void acceptThrows(@NotNull User u, @NotNull PaginationEventWrapper wrappe
timeout.cancel(true);
}
if (helper.getTimeout() > 0) {
timeout = worker.schedule(() -> finalizeEvent(msg, success), helper.getTimeout(), TimeUnit.MILLISECONDS);
timeout = scheduler.schedule(evt, () -> finalizeEvent(msg, success), helper.getTimeout(), TimeUnit.MILLISECONDS);
}

if (wrapper.isFromGuild() && wrapper.getSource() instanceof MessageReactionAddEvent && paginator.isRemoveOnReact()) {
Expand Down Expand Up @@ -1165,21 +1167,22 @@ public static ActionReference buttonize(@NotNull Message msg, @NotNull Buttonize
}
}

return handler.addEvent(msg, new ThrowingBiConsumer<>() {
String evt = handler.getEventId(msg);
return handler.addEvent(evt, new ThrowingBiConsumer<>() {
private ScheduledFuture<?> timeout;
private final Consumer<Void> success = s -> {
if (timeout != null) {
timeout.cancel(true);
}

handler.removeEvent(msg);
handler.removeEvent(evt);
if (helper.getOnFinalization() != null) helper.getOnFinalization().accept(msg);
if (paginator.isDeleteOnCancel()) msg.delete().submit();
};

{
if (helper.getTimeout() > 0) {
timeout = worker.schedule(() -> finalizeEvent(msg, success), helper.getTimeout(), TimeUnit.MILLISECONDS);
timeout = scheduler.schedule(evt, () -> finalizeEvent(msg, success), helper.getTimeout(), TimeUnit.MILLISECONDS);
}
}

Expand Down Expand Up @@ -1243,7 +1246,7 @@ public void acceptThrows(@NotNull User u, @NotNull PaginationEventWrapper wrappe
timeout.cancel(true);
}
if (helper.getTimeout() > 0) {
timeout = worker.schedule(() -> finalizeEvent(msg, success), helper.getTimeout(), TimeUnit.MILLISECONDS);
timeout = scheduler.schedule(evt, () -> finalizeEvent(msg, success), helper.getTimeout(), TimeUnit.MILLISECONDS);
}

if (wrapper.isFromGuild() && wrapper.getSource() instanceof MessageReactionAddEvent && paginator.isRemoveOnReact()) {
Expand Down Expand Up @@ -1507,23 +1510,24 @@ public static ActionReference lazyPaginate(@NotNull Message msg, @NotNull LazyPa
addReactions(msg, false, false);
}

return handler.addEvent(msg, new ThrowingBiConsumer<>() {
String evt = handler.getEventId(msg);
return handler.addEvent(evt, new ThrowingBiConsumer<>() {
private int p = 0;
private ScheduledFuture<?> timeout;
private final Consumer<Void> success = s -> {
if (timeout != null) {
timeout.cancel(true);
}

handler.removeEvent(msg);
handler.removeEvent(evt);
if (paginator.isDeleteOnCancel()) msg.delete().submit();
};

private final Function<Button, Button> LOWER_BOUNDARY_CHECK = b -> b.withDisabled(p == 0);

{
if (helper.getTimeout() > 0) {
timeout = worker.schedule(() -> finalizeEvent(msg, success), helper.getTimeout(), TimeUnit.MILLISECONDS);
timeout = scheduler.schedule(evt, () -> finalizeEvent(msg, success), helper.getTimeout(), TimeUnit.MILLISECONDS);
}
}

Expand Down Expand Up @@ -1601,7 +1605,7 @@ public void acceptThrows(@NotNull User u, @NotNull PaginationEventWrapper wrappe
timeout.cancel(true);
}
if (helper.getTimeout() > 0) {
timeout = worker.schedule(() -> finalizeEvent(msg, success), helper.getTimeout(), TimeUnit.MILLISECONDS);
timeout = scheduler.schedule(evt, () -> finalizeEvent(msg, success), helper.getTimeout(), TimeUnit.MILLISECONDS);
}

if (wrapper.isFromGuild() && wrapper.getSource() instanceof MessageReactionAddEvent && paginator.isRemoveOnReact()) {
Expand Down
32 changes: 32 additions & 0 deletions src/main/java/com/github/ygimenez/model/TaskScheduler.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.github.ygimenez.model;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;

/**
* Task manager for pagination events' expiration
*/
public class TaskScheduler {
private final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();
private final Map<String, ScheduledFuture<?>> tasks = new HashMap<>();

/**
* Schedule a new task, cancelling and replacing the previous if exists.
*
* @param id The task identifier.
* @param task The task itself.
* @param time The time for the timeout.
* @param unit The unit for the timeout.
* @return
*/
public ScheduledFuture<?> schedule(String id, Runnable task, long time, TimeUnit unit) {
ScheduledFuture<?> t = worker.schedule(task, time, unit);
ScheduledFuture<?> prev = tasks.put(id, t);
if (prev != null) {
prev.cancel(true);
}

return t;
}
}

0 comments on commit 7a0d0ab

Please sign in to comment.