java.lang.IllegalStateException:即使我正在创建类本身的新实例,计时器也已取消

发布于 2024-12-01 07:47:43 字数 956 浏览 4 评论 0原文

问题陈述:我有一堂课,里面有一个计时器。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

思念绕指尖 2024-12-08 07:47:43

timerStatic 被声明为static,这意味着 DeleteTimer 的所有实例共享同一个 timerStatic 实例。

如果您删除 start 方法和 timerStatic 上的 static 修饰符,这将阻止类的不同实例相互干扰。

timerStatic is declared static, which means that all instances of DeleteTimer share the same instance of timerStatic.

If you remove the static modifier on both the start method and timerStatic, this will stop different instances of your class interfering with each other.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文