java.lang.IllegalStateException:即使我正在创建类本身的新实例,计时器也已取消
问题陈述:我有一堂课,里面有一个计时器。
class DeleteTimer {
private Timer timer = new Timer();
private static Timer timerStatic;
public DeleteTimer(Member uid, String serverFilePath, String deleteTime) {
}
public static void start() {
timerStatic.schedule(new TimerTask() {
public void run() {
deleteFolder();
try {
timerStatic.cancel();
} catch (Exception e) {
e.printStackTrace();
}
}
private void deleteFolder() {
//delete a folder
return true;
}
}, 10000);
}
}
我有一个程序可以创建一些文件夹,我希望这些文件夹在一段时间后自动删除。文件夹的名称不固定,因此每次调用此类时,我都会为其创建一个新对象。
DeleteTimer obj = new DeleteTimer();
obj.start();
第一次尝试时效果很好,但当我尝试使用新对象运行它时,会出现 java.lang.IllegalStateException: Timer hascancelled 。请帮忙。
Problem statement: I have a class that has a timer in it.
class DeleteTimer {
private Timer timer = new Timer();
private static Timer timerStatic;
public DeleteTimer(Member uid, String serverFilePath, String deleteTime) {
}
public static void start() {
timerStatic.schedule(new TimerTask() {
public void run() {
deleteFolder();
try {
timerStatic.cancel();
} catch (Exception e) {
e.printStackTrace();
}
}
private void deleteFolder() {
//delete a folder
return true;
}
}, 10000);
}
}
I have a program that creates some folders and I want that those folders to be deleted automatically after some time. the name of the folders are not fixed and hence every time I call this class, I create a new object for it.
DeleteTimer obj = new DeleteTimer();
obj.start();
This works fine at first attempt, but gives java.lang.IllegalStateException: Timer already cancelled
when I try to run it using a new object. Please help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
timerStatic
被声明为static
,这意味着DeleteTimer
的所有实例共享同一个timerStatic
实例。如果您删除
start
方法和timerStatic
上的static
修饰符,这将阻止类的不同实例相互干扰。timerStatic
is declaredstatic
, which means that all instances ofDeleteTimer
share the same instance oftimerStatic
.If you remove the
static
modifier on both thestart
method andtimerStatic
, this will stop different instances of your class interfering with each other.