Skip to content

Commit b89ebfa

Browse files
committed
Added cleanup functionality and changed task behavior
1 parent 5cde47d commit b89ebfa

File tree

6 files changed

+183
-110
lines changed

6 files changed

+183
-110
lines changed

src/main/java/com/github/bustedearlobes/themis/commands/MuteCommand.java

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -25,22 +25,23 @@ public void onCall(Matcher parsedCommand, Message message, JDA jda, Themis themi
2525
if(message.getMentionedChannels().size() > 0) {
2626
channel = message.getMentionedChannels().get(0);
2727
}
28-
MuteToggleTask muteTask = new MuteToggleTask(message.getMentionedUsers(),
29-
channel,
30-
message.getTextChannel(),
31-
true);
32-
themis.getTaskManager().addTask(muteTask);
3328
if(parsedCommand.group(4) != null) {
3429
TimeUnit timeUnit = parseTimeUnit(parsedCommand.group(6));
3530
long time = Integer.parseInt(parsedCommand.group(5));
3631
MuteToggleTask unmuteTask = new MuteToggleTask(
3732
message.getMentionedUsers(),
3833
channel,
3934
message.getTextChannel(),
40-
false,
35+
true,
4136
time,
4237
timeUnit);
4338
themis.getTaskManager().addTask(unmuteTask);
39+
} else {
40+
MuteToggleTask muteTask = new MuteToggleTask(message.getMentionedUsers(),
41+
channel,
42+
message.getTextChannel(),
43+
true);
44+
themis.getTaskManager().addTask(muteTask);
4445
}
4546
}
4647
}

src/main/java/com/github/bustedearlobes/themis/commands/UnmuteCommand.java

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,9 +29,7 @@ public void onCall(Matcher parsedCommand, Message message, JDA jda, Themis themi
2929
message.getMentionedUsers(),
3030
channel,
3131
message.getTextChannel(),
32-
false,
33-
0,
34-
TimeUnit.SECONDS);
32+
false);
3533
themis.getTaskManager().addTask(unmuteTask);
3634
}
3735
}

src/main/java/com/github/bustedearlobes/themis/taskmanager/MuteToggleTask.java

Lines changed: 40 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import java.util.ArrayList;
44
import java.util.List;
55
import java.util.concurrent.TimeUnit;
6+
import java.util.logging.Level;
67
import java.util.logging.Logger;
78

89
import net.dv8tion.jda.core.Permission;
@@ -16,12 +17,14 @@ public class MuteToggleTask extends ScheduledTask {
1617
private static final long serialVersionUID = 1L;
1718
private static Logger LOG = Logger.getLogger("Themis");
1819

19-
List<String> targetUserIds = new ArrayList<String>();
20+
private List<String> targetUserIds = new ArrayList<String>();
2021

21-
String targetGuildId;
22-
String targetTextChannelId;
23-
String targetLogChannelId;
24-
boolean mute;
22+
private String targetGuildId;
23+
private String targetTextChannelId;
24+
private String targetLogChannelId;
25+
private boolean shouldMute;
26+
private TimeUnit timeUnit = null;
27+
private long time = 0;
2528

2629
public MuteToggleTask(List<User> targets,
2730
TextChannel textChannel,
@@ -34,27 +37,49 @@ public MuteToggleTask(List<User> targets,
3437
this.targetGuildId = textChannel.getGuild().getId();
3538
this.targetTextChannelId = textChannel.getId();
3639
this.targetLogChannelId = logChannel.getId();
37-
this.mute = mute;
40+
this.shouldMute = mute;
3841
}
3942

43+
/**
44+
* This constructor is used to mute a player for a certain amount of time.
45+
* @param targets
46+
* @param textChannel
47+
* @param logChannel
48+
* @param mute
49+
* @param time
50+
* @param timeUnit
51+
*/
4052
public MuteToggleTask(List<User> targets,
4153
TextChannel textChannel,
4254
TextChannel logChannel,
4355
boolean mute,
4456
long time,
4557
TimeUnit timeUnit) {
46-
super(time, 0, timeUnit, 0);
58+
super(0, 0, TimeUnit.MICROSECONDS, 0);
4759
for(User user : targets) {
4860
targetUserIds.add(user.getId());
4961
}
5062
this.targetGuildId = textChannel.getGuild().getId();
5163
this.targetTextChannelId = textChannel.getId();
5264
this.targetLogChannelId = logChannel.getId();
53-
this.mute = mute;
65+
this.shouldMute = mute;
66+
this.time = time;
67+
timeUnit = this.timeUnit;
5468
}
5569

5670
@Override
5771
protected void runTask() {
72+
toggleMute(shouldMute);
73+
if(timeUnit != null) {
74+
try {
75+
timeUnit.sleep(time);
76+
} catch(InterruptedException e) {
77+
LOG.log(Level.SEVERE, "Interrupted sleep", e);
78+
}
79+
}
80+
}
81+
82+
private void toggleMute(boolean mute) {
5883
Guild guild = getGuildById(targetGuildId);
5984
TextChannel channel = getTextChannelById(targetTextChannelId, guild);
6085
String[] userNames = new String[targetUserIds.size()];
@@ -93,5 +118,12 @@ protected void runTask() {
93118
TextChannel logChannel = getTextChannelById(targetLogChannelId, guild);
94119
logChannel.sendMessage(muteString + " " + userNamesFormated).complete();
95120
}
121+
122+
@Override
123+
protected void cleanUpJDAChanges() {
124+
if(timeUnit != null) {
125+
toggleMute(!shouldMute);
126+
}
127+
}
96128

97129
}

src/main/java/com/github/bustedearlobes/themis/taskmanager/ScheduledTask.java

Lines changed: 82 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
import java.io.Serializable;
44
import java.util.concurrent.TimeUnit;
5-
import java.util.concurrent.atomic.AtomicBoolean;
65
import java.util.logging.Level;
76
import java.util.logging.Logger;
87

@@ -16,54 +15,113 @@
1615
import net.dv8tion.jda.core.hooks.ListenerAdapter;
1716

1817
public abstract class ScheduledTask extends ListenerAdapter implements Runnable, Serializable {
19-
private static final long serialVersionUID = 1L;
18+
private static final long serialVersionUID = 2L;
2019
private static final Logger LOG = Logger.getLogger("Themis");
2120

21+
private final String NAME = this.getClass().getName();;
22+
2223
private long periodicity;
2324
private long repeat;
24-
private long numberOfRuns;
25-
private AtomicBoolean isComplete;
26-
private AtomicBoolean isInProgress;
25+
private long numberOfRuns = 0;
26+
private TaskState state;
27+
2728
private transient long timeOfNextRun;
2829
private transient JDA jda;
30+
2931

3032
public ScheduledTask(long delay, long periodicity, TimeUnit timeUnit, long repeat) {
3133
this.periodicity = timeUnit.toMillis(periodicity);
3234
this.timeOfNextRun = System.currentTimeMillis() + timeUnit.toMillis(delay);
3335
this.repeat = repeat;
34-
this.numberOfRuns = 0;
35-
this.isComplete = new AtomicBoolean(false);
36-
this.isInProgress = new AtomicBoolean(false);
36+
setState(TaskState.QUEUED);
3737
}
3838

39-
protected boolean taskIsReady() {
40-
return (System.currentTimeMillis() >= timeOfNextRun) && !isExpired();
39+
@Override
40+
public final void run() {
41+
setState(TaskState.RUNNING);
42+
jda.addEventListener(this);
43+
try {
44+
runTask();
45+
} catch(Exception e) {
46+
StackTraceElement[] st = e.getStackTrace();
47+
if(st.length > 0) {
48+
StackTraceElement lastStackTrace = st[st.length - 1];
49+
LOG.logp(Level.WARNING, lastStackTrace.getClassName(), lastStackTrace.getMethodName(),
50+
"Exception occured in scheduled task.", e);
51+
} else {
52+
LOG.log(Level.WARNING, "Exception occured in scheduled task.", e);
53+
}
54+
} finally {
55+
jda.removeEventListener(this);
56+
this.cleanUpTask();
57+
}
58+
if(hasMoreRuns()) {
59+
setState(TaskState.QUEUED);
60+
} else {
61+
setState(TaskState.CLEANUP);
62+
}
63+
}
64+
65+
public final boolean isSameTaskType(ScheduledTask task) {
66+
return (this.NAME == task.NAME);
67+
}
68+
69+
public boolean isState(TaskState state) {
70+
synchronized(this.state) {
71+
return (this.state == state);
72+
}
73+
}
74+
75+
public TaskState getState() {
76+
synchronized(state) {
77+
return state;
78+
}
79+
}
80+
81+
protected void cleanUpTask() {
82+
cleanUpJDAChanges();
83+
setState(TaskState.DEAD);
84+
}
85+
86+
protected final long getTimeUntilNextRun() {
87+
return timeOfNextRun - System.currentTimeMillis();
88+
}
89+
90+
protected final void incrementRun() {
91+
timeOfNextRun = System.currentTimeMillis() + periodicity;
92+
if(repeat != Long.MAX_VALUE) {
93+
numberOfRuns++;
94+
}
95+
}
96+
97+
protected final boolean taskIsReady() {
98+
return (System.currentTimeMillis() >= timeOfNextRun);
4199
}
42100

43-
protected boolean isExpired() {
44-
return ((numberOfRuns > repeat) && isComplete());
101+
protected final boolean hasMoreRuns() {
102+
return (numberOfRuns > repeat);
45103
}
46104

47-
protected JDA getJDA() {
105+
protected final JDA getJDA() {
48106
if(jda == null) {
49107
LOG.log(Level.SEVERE, "JDA not set in task");
50108
}
51109
return jda;
52110
}
53111

54-
protected void setJDA(JDA jda) {
112+
protected final void setJDA(JDA jda) {
55113
this.jda = jda;
56114
}
57115

58-
protected Guild getGuildById(String guildId) {
116+
protected final Guild getGuildById(String guildId) {
59117
Guild guild = getJDA().getGuildById(guildId);
60118
if(guild == null) {
61119
throw new EntityNotFoundException("Could not find group from id " + guildId);
62120
}
63121
return guild;
64122
}
65123

66-
protected Member getMemberById(String memberId, Guild guild) {
124+
protected final Member getMemberById(String memberId, Guild guild) {
67125
Member member = guild.getMemberById(memberId);
68126
if(member == null) {
69127
throw new EntityNotFoundException("Could not find member from id "
@@ -74,7 +132,7 @@ protected Member getMemberById(String memberId, Guild guild) {
74132
return member;
75133
}
76134

77-
protected TextChannel getTextChannelById(String textChannelId, Guild guild) {
135+
protected final TextChannel getTextChannelById(String textChannelId, Guild guild) {
78136
TextChannel textChannel = guild.getTextChannelById(textChannelId);
79137
if(textChannel == null) {
80138
throw new EntityNotFoundException("Could not find textChannel from id "
@@ -85,58 +143,22 @@ protected TextChannel getTextChannelById(String textChannelId, Guild guild) {
85143
return textChannel;
86144
}
87145

88-
protected User getUserById(String userId) {
146+
protected final User getUserById(String userId) {
89147
User user = jda.getUserById(userId);
90148
if(user == null) {
91149
throw new EntityNotFoundException("Could not find user from id " + userId);
92150
}
93151
return user;
94152
}
95-
96-
@Override
97-
public final void run() {
98-
isInProgress.set(true);
99-
jda.addEventListener(this);
100-
try {
101-
runTask();
102-
} catch(Exception e) {
103-
StackTraceElement[] st = e.getStackTrace();
104-
if(st.length > 0) {
105-
StackTraceElement lastStackTrace = st[st.length - 1];
106-
LOG.logp(Level.WARNING, lastStackTrace.getClassName(), lastStackTrace.getMethodName(),
107-
"Exception occured in scheduled task.", e);
108-
} else {
109-
LOG.log(Level.WARNING, "Exception occured in scheduled task.", e);
110-
}
111-
} finally {
112-
jda.removeEventListener(this);
113-
}
114-
isComplete.set(true);
115-
isInProgress.set(false);
116-
}
117-
118-
public final void incrementRun() {
119-
timeOfNextRun = System.currentTimeMillis() + periodicity;
120-
if(repeat != Long.MAX_VALUE) {
121-
numberOfRuns++;
122-
}
123-
}
124153

125-
public boolean isComplete() {
126-
return isComplete.get();
127-
}
154+
protected void cleanUpJDAChanges() { }
128155

129-
public void recalculateRunTime(long timeRemaining) {
130-
timeOfNextRun = System.currentTimeMillis() + timeRemaining;
131-
}
156+
protected abstract void runTask();
132157

133-
public long getTimeUntilNextRun() {
134-
return timeOfNextRun - System.currentTimeMillis();
158+
private void setState(TaskState state) {
159+
synchronized(this.state) {
160+
this.state = state;
161+
}
135162
}
136163

137-
protected abstract void runTask();
138-
139-
public boolean isInProgress() {
140-
return isInProgress.get();
141-
}
142164
}

0 commit comments

Comments
 (0)