Furari
Furari

Reputation: 33

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.

Upvotes: 3

Views: 82

Answers (3)

Michał Turczyn
Michał Turczyn

Reputation: 37357

Try changing your 1000 to amount of milliseconds you want. This 1000 means the second you are waiting. Also you could try Thread.sleep() function, if it is a option.

Remember that values passed to that function are in milliseconds.

Upvotes: 0

Raman Sahasi
Raman Sahasi

Reputation: 31841

The value 1000 in your code is actually a milliseconds value.

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

You can change it according to your requirements. Like if you want to wait for 5 seconds, you can change it to 5 * 1000 = 5000.

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

Upvotes: 0

GhostCat
GhostCat

Reputation: 140427

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);

Upvotes: 4

Related Questions