Furari Furari -4 years ago 57
Java Question

Timed Print Line

How can I print line in x millisecond and print word x millisecond after the previous one?

I'm trying to make a 'Lyric Video' in console. I've tried using

t.schedule(new TimerTask(){public void run(){System.out.print("");}}, 0, 1000);


But it prints words EVERY second.

I've tried Google but I can't seem to get the words right.

Answer Source

Here:

t.schedule(new TimerTask(){public void run(){System.out.print("");}}, 0, 1000);

That 1000 gives the number of milliseconds when that timed task is executed.

Or more precisely: period - time in milliseconds between successive task executions.

So: just change that to your x value.

And the real answer here: don't just blindly use some API you find somewhere. When in doubt, turn to the javadoc and read what the methods you are calling are doing, like for schedule(). There you would have found that information I quoted above!

Regarding your follow-on questions: again; turn to the javadoc for the Timer class. That class has to methods cancel() and purge() which you can use to prevent future executions.

In other words:

  • change 1000 to 5000 to change the delay between print statements
  • if you want to stop after a certain iteration, just make sure to call one of the aforementioned methods at some point.

So, when you want to stop after 10 seconds, you could do something like:

t.schedule(new TimerTask(){public void run(){ t.cancel();}}, 10 
1000);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download