我正在编程一个不和谐的机器人,并希望在某个时候运行一个取消禁令。然而,即使日期是未来的,TimerTask也不会被调用。如果日期是过去的,则计时器任务将立即调用。我试着公布一些数据,看看日期是否错误,但它是正确的。
我只想叫一次。
System.out.println("started");
System.out.println(date);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("called");
user.openPrivateChannel().complete().sendMessage(
"**-Unban-**" +
"\n" +
"Du wurdest entbannt!"
).queue();
guild.removeRoleFromMember(user.getId(), guild.getRoleById("690579286582624276")).queue();
guild.addRoleToMember(user.getId(), guild.getRoleById("688733671104053327")).queue();
}
}, date);控制台输出:
started
Fri Mar 20 17:21:55 UTC 2020希望你能发现!
发布于 2020-03-20 16:53:00
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class Main {
Date date = new Date();// Initialize it as per your requirement
Timer timer = new Timer();
TimerTask task = new TimerTask() {
public void run() {
System.out.println("called");
//...
timer.cancel();
}
};
public void start() {
timer.schedule(task, date);
}
public static void main(String[] args) {
Main timer = new Main();
timer.start();
}
}发布于 2020-03-20 16:58:22
若要使用计时器,应执行下一个步骤
scheduleAtFixedRate
示例
Reloj.scheduleAtFixedRate(新的Reloj(),0,1000);
你可以做下一个
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication11;
import java.util.TimerTask;
/**
*
* @author Sem-6-INGENIERIAINDU
*/
public class Reloj extends TimerTask{
@Override
public void run() {
// Your code
}
}类实现计时器/* *以更改此许可头,在Properties中选择许可头。*若要更改此模板文件,请选择Tools 000-Template*并在编辑器中打开该模板。*/包javaapplication11;
import java.util.Timer;
/**
*
* @author Sem-6-INGENIERIAINDU
*/
public class JavaApplication11 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Timer reloj=new Timer();
reloj.scheduleAtFixedRate(new Reloj(), 0, 1000);
}
}结果是
运行: Corriendo构建停止(总时间:1分10秒)
https://stackoverflow.com/questions/60778313
复制相似问题