开发者

java.lang.IllegalStateException: Timer already cancelled even when i am creating a new instance of the class itself

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 = ne开发者_如何学JAVAw 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜