我正在尝试在JDA中创建倒计时计时器。不过,我认为我做得不对。输入的原始命令将不断编辑以显示正在进行的倒计时。倒计时的最大时间为48小时,如for循环所示。这是我的代码:
@Override
public void onGuildMessageReceived(GuildMessageReceivedEvent event) {
super.onGuildMessageReceived(event);
//!countdown hours:minutes:seconds
if (event.getMessage().getContentRaw().startsWith("!countdown")) {
String timebuilder = "";
char[] chararr = event.getMessage().getContentRaw().toCharArray();
for (int i = 11; i < chararr.length; i++) {
timebuilder += chararr[i];
}
// event.getChannel().sendMessage(timebuilder).queue();
int hour = Integer.parseInt(timebuilder.substring(0, 1));
int minute = Integer.parseInt(timebuilder.substring(3, 4));
int second = Integer.parseInt(timebuilder.substring(6, 7));
for (int i = 0; i < 172800; i++ ) {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 0 0 0
if (hour == 0 && minute == 0 && second == 0) {
event.getMessage().editMessage("00:00:00");
event.getChannel().sendMessage("Countdown complete!").queue();
break;
}
// 0 1 1
else if (hour == 0 && minute > 0 && second > 0) {
minute--;
second--;
event.getMessage().editMessage(hour + ":" + minute + ":" + second).queue();;
}
//0 1 0
else if (hour == 0 && minute > 0 && second == 0) {
minute--;
second = 59;
event.getMessage().editMessage(hour + ":" + minute + ":" + second).queue();;
}
//1 0 0
else if (hour > 0 && minute == 0 && second == 0) {
second = 59;
minute = 59;
hour--;
event.getMessage().editMessage(hour + ":" + minute + ":" + second).queue();;
}
//0 0 1 //1 0 1 //1 1 1
else if ((hour == 0 && minute == 0 && second > 0) || (hour > 0 && minute == 0 && second > 0) || (hour > 0 && minute > 0 && second > 0)) {
second--;
event.getMessage().editMessage(hour + ":" + minute + ":" + second).queue();
}
//1 1 0
else if (hour > 0 && minute > 0 && second == 0) {
minute--;
event.getMessage().editMessage(hour + ":" + minute + ":" + second).queue();
}
}
}
}
似乎有一种更简单的方法可以做到这一点。使用Timer或SimpleDateFormat或其他东西,但我只是不知道那会是什么。出于某种原因,我的消息没有使用. editMessage()
方法进行编辑。
输出:
!countdown 01:02:02 //user keyed discord bot command
对于预期输出,“!倒计时01:02:02”消息应使用更新的倒计时不断编辑。如下所示:
预期输出:
!countdown 01:02:02 //user keyed discord bot command
01:02:01 //original command
01:02:00 //original command
01:01:59 //original command
etc...
您应该能够使用Timer和TimerTask,Timer用于调度Timer任务。定时器用于在线程后台调度任务,如下所示:
TimerTask task = new TimerTask(){
public void run(){
System.out.println("Code to be executed");
}
};
Timer timer = new Timer();
// The delay period is calculated in milliseconds iirc
timer.schedule(task, 5*1000);