Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Invoke thread at specific time ... ?

 
Vijay S. Rathore
Ranch Hand
Posts: 449
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How to invoke a thread daily at a specific time?

For example I want to invoke a thread every day at 12.00 A.M.

I tried to use

public void scheduleAtFixedRate(TimerTask task, Date firstTime, long period)
from java.util.Timer class. But it needs the second parameter as miliseconds.

Any links or suggestions will help.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A day is 1000 milliseconds times 60 seconds times 60 minutes times 24 hours; 1000*60*60*24, or 86400000 milliseconds. I generally prefer to write out the arithmetic in the code, as it is perhaps clearer and is less prone to error.
 
Vijay S. Rathore
Ranch Hand
Posts: 449
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That I already got, but how to find out the milliseconds at 12 A.M.?

in other words, what should be the output of following program

public class TimerThread extends TimerTask {

public TimerThread() {
super();
}

public void run() {
System.out.println("Thread is running now ...");
System.out.println("Thread is Stopped now ...");
}

public static void main(String [] x){
System.out.println(new Date().getTime());
System.out.println(new Date().getTime() + 2000);
(new Timer()).scheduleAtFixedRate(new TimerThread(), (new Date().getTime() + 1000), 2000);
}
}
[ August 11, 2004: Message edited by: Vijay Rathore ]
 
Vijay S. Rathore
Ranch Hand
Posts: 449
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't worry I got it. The second parameter is the initial invocation of thread. I have to find out the difference of miliseconds at 12 A.M. and current miliseonds and then pass the difference as second parameter.

Thanks anyway
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sometimes asking the question is the best way to see the answer, no? Glad you found that. Timer is very cool, but may be mild overkill in extremely simple situations. You can make your own thread that just sleeps that long, too.
 
Vijay S. Rathore
Ranch Hand
Posts: 449
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's what is the purpose of pair programming.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic