英文:
Stopping a timer in java
问题
抱歉再次打扰。
我在停止计时器方面遇到了问题。
我尝试使用一个布尔值,在运行一次后,它会获得一个 false 的值,然后取消计时器,但是这并没有成功。
计时器应该在特定时间运行一次。使用 timer.cancel() 可以在任务运行之前取消计时器。
我想到可以在日期上加上几毫秒,这样就可以停止它(连同 timer.cancel()),但是这并没有起作用。
我将代码告诉你:
public class MyTimeTask extends TimerTask {
private String name;
public MyTimeTask(String name) {
this.name = name;
}
@Override
public void run() {
System.out.println(this.name);
}
}
public static void main(String[] args) throws ParseException {
DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String yearMonth = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM"));
String day = "05";
Date date = dateFormatter.parse(yearMonth + "-" + day + " 02:10:08PM");
System.out.println(yearMonth);
Timer timer = new Timer();
TimerTask task = new MyTimeTask("Patrick");
timer.schedule(task, date);
long expiremilis = 10l;
Date expireDate = new Date(date.getTime() + expiremilis);
timer.cancel();
}
这是我尝试解决问题的一种方式,但是我无法成功,也不知道是否适合在所选日期上添加毫秒数来停止它。
我做错了什么?
谢谢
英文:
sorry for bothering again.
I'm having troubles with stopping a timer.
I tried doing a boolean to which, after one run, it would get a false value and then cancel the timer, but it didn't work out.
The timer is supposed to run once at a specific time. Using timer.cancel() it canceled before running the task.
I figured that I could add a couple of milliseconds to the date so that it would stop (along with the timer.cancel()), but it didn't work.
I'm letting you know the code:
public class MyTimeTask extends TimerTask {
private String name;
public MyTimeTask(String name) {
this.name = name;
}
@Override
public void run() {
System.out.println(this.name);
}
}
public static void main(String[] args) throws ParseException {
DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String yearMonth = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM"));
String day = "05";
Date date = dateFormatter.parse(yearMonth + "-" + day + " 02:10:08PM");
System.out.println(yearMonth);
Timer timer = new Timer();
TimerTask task = new MyTimeTask("Patrick");
timer.schedule(task, date);
long expiremilis = 10l;
Date expireDate = new Date(date.getTime() + expiremilis);
timer.cancel();
}
This was one of the ways I tried to fix this, but I couldn't, nor do I know if adding milliseconds to the chosen date is appropriate at all to make it stop.
What am I doing wrong?
Thanks
专注分享java语言的经验与见解,让所有开发者获益!
评论