基本上,您需要创建一个包含消息的数组和一个在 0 和最后一条消息之间交替的索引:
String[] messages={"message 1","message 2"};
int currentIndex=0;
每 30 秒,您可以执行以下操作:
jda.getPresence().setActivity(Activity.playing(messages[currentIndex]));
currentIndex=(currentIndex+1)%messages.length;
首先是这个sets the Activity to the current message(currentIndex数组中的元素)。
在此之后,它将1 添加到currentIndex。
如果currentIndex 超出数组长度,它会再次将其设置为0。这是使用Modulo operation 完成的。
为了每 30 秒执行一次,您可以使用以下方法之一:
java.util.Timer
执行此操作的旧方法是创建Timer:
//Outside of any method
private String[] messages={"message 1","message 2"};
private int currentIndex=0;
//Run this once
new Timer().schedule(new TimerTask(){
public void run(){
jda.getPresence().setActivity(Activity.playing(messages[currentIndex]));
currentIndex=(currentIndex+1)%messages.length;
}},0,30_000);
Timer#schedule 可以在特定延迟后执行TimerTask(0 表示您想立即开始)并让它在指定时间段后重复(延迟时间和时间段均以毫秒为单位)。
java.util.concurrent.ScheduledExecutorService
也可以使用ScheduledExecutorService,它允许更多的定制(这种方法被认为比Timer“更好”,如Java Concurrency in Practice,第6.2.5章所述):
//outside of any method
private String[] messages = { "message 1", "message 2" };
private int currentIndex = 0;
private ScheduledExecutorService threadPool = Executors.newSingleThreadScheduledExecutor();
//run this once
threadPool.scheduleWithFixedDelay(() -> {
jda.getPresence().setActivity(Activity.playing(messages[currentIndex]));
currentIndex = (currentIndex + 1) % messages.length;
}, 0, 30, TimeUnit.SECONDS);
//when you want to stop it (e.g. when the bot is stopped)
threadPool.shutdown();
首先,创建一个允许调度任务的线程池。
这个线程池也可以用于其他任务。
在此示例中,这是使用单个线程完成的。如果要使用多线程,可以使用Executors.newScheduledThreadPool(numberOfThreads);。
在此之后,您调用 ScheduledExecutorService#scheduleWithFixedDelay,它会每 30 秒运行一次提供的 Runnable。
如果您希望它在应用程序停止时自动停止而不调用shutdown(),您可以通过指定ThreadFactory 来告诉它使用守护线程:
ScheduledExecutorService threadPool = Executors.newSingleThreadScheduledExecutor(r->{
Thread t=new Thread(r);
t.setDaemon(true);
return t;
});