Closed Squidkingdom closed 7 years ago
Create a second thread for the timer.
Exactly. If you are on Java8 you might want to have a look Into ScheduledExecutorService :) Maybe if one day I will take the time to pack my CooldownHandler and Commands in a library I will note you, if that is fine @Squidkingdom
Thanks!
So I looked into the ScheduledExecutorService and most of it goes over my head. :P I cant seem to find anything that explains how to use it w/o doing very complicated stuff. Any tips or mabye some code to help me start. Thanks for your time, Squid
Im especially struggling on how to get another class to use sendMessage() without creating another bot.
There's a bunchhhh of aproches on making this. The easiest don't know if the most eficient is to make the bot variable static
Not picking up on what your saying, Im but a humble joe, trying to say a message on a timer and not knowing how. XD I still cant find anything that illustrates how to use ScheduledExecutorService.
You will give your bot a new variable:
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
and another one that tells whether to send the message or not:
boolean sending = false;
so that you can turn on the messages when the bot is connected.
Then you give your bot two new methods to start/stop the Executor:
public void startExec() {
if (executorService.isShutdown()) {
executorService = Executors.newSingleThreadScheduledExecutor();
}
executorService.scheduleAtFixedRate(this::autoMessage, 1, 1, TimeUnit.MINUTES);
}
public void stopExec() {
executorService.shutdown();
}
And then at last you need a method that is executed be the service (and I called it autoMessage here):
private void autoMessage() {
if (sending) {
this.sendMessage("Hello, World!", Channel.getChannel("channelOfYourChoice"));
}
}
So what happens here? Calling the startExec() method will create a new ExecutorService that will execute the specified method (this::autoMessage beeing a different notation for this.autoMessage() , that is needed in Java8) after an initial delay of 1 (TimeUnit) every 1 (TimeUnits) with TimeUnit beeing Minutes here.
So you change sending
to true when your bot is connected or you want to have it sending later. You can change the parameters of the ExecutorService after you choice: (object::method, initialDelay, period, timeUnit). You can as well call static methods with Class::method if needed.
Ok so I would do this in another class?
and I would call startExec()
to start the timer? @geisterfurz007
The methods above would go into your bot class and exactly startExec()
would then start the timer. I am unsure in how far you need sending
. If you do not feel like you need it, take it out :)
ok Thanks
Is there a way I'm not seeing to send a message on a timer every so often like moobot or something would do? I can't find a way to do it without stopping the bot in it tracks. Please Help!