1

I've got this:

import java.util.Timer;
import java.util.TimerTask;

    public class useTimerTask {
        public static void main(String[] args){
            Timer timer = new Timer(true);
            timer.schedule(new TimerTask() {
                public void run() {
                    System.out.println("abc");
                }
            }, 200000 , 1000);
        }
    }

I expected that after I run this program, there will be periodic output on screen. But when I run it inside intelliJ, seems it finishes immediately without printing anything.

What happened? How to fix it?

3
  • 1
    I'd say Timer is non-blocking and the main thread stops immediately. A workaround with a locking/blocking object is shown here Commented Nov 30, 2018 at 13:42
  • Sharing the error logs would be helpful to find a solution Commented Nov 30, 2018 at 13:42
  • You have to wait for your timer in your main thread Commented Nov 30, 2018 at 13:43

1 Answer 1

3

First of all, you need to remove the parameter from the Timer's constructor. By passing true you specify that the thread is a "deamon": a daemon thread does not prevent the JVM from exiting when all non-daemon threads are finished.

Second thing is that you set delay parameter to 200 minutes. It means that you have to wait 200 minute before program starts repeating println. Below is working version:

       Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                System.out.println("abc");
            }
        }, 100 , 1000);

If you set your Timer as a deamon the JVM will see that there is no active threads and just stop terminate your program when the instruction of scheduling timer have finished. But if you remove parameter "true" from Timer constructor it will be visible as an active thread it means that program won't stop until this timer finish his job.

Below code shows this situation. Timer will work for 10 seconds because you sleep main thread and timer (deamon) will work until this sleep has finished.

    Timer timer = new Timer(true);
    timer.schedule(new TimerTask() {
        public void run() {
            System.out.println("abc");
        }
    }, 100 , 1000);

    try {
        Thread.sleep(10000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.