Ok, so basically I have a program that's simulating something and occasionally I want to start a timer that will create a new thread, wait for the specified amount of time, then send a notification back in the original program.
The problem I'm having is that the timer will start and go off, but not after the correct specified time... Here's my code to make it clearer:
I'm calling it from another class with the following code:public class NewTimer { Timer timer; static int current_num; static long start_time; public NewTimer(long milliseconds, int curr_num) { current_num =curr_num; timer = new Timer(); timer.schedule(new RemindTask(), milliseconds); start_time = System.currentTimeMillis(); } class RemindTask extends TimerTask { public void run() { System.out.println("Time Elapsed: " + (System.currentTimeMillis() - start_time)); timer.cancel(); }}}
new NewTimer(temp_time, current_num);
The problem is that the "Time Elapsed" is often significantly (2-3x) bigger than the time sent into the timer. I'm at my wits end trying to figure out why and I feel it must be a misunderstanding on my part about threads or something. When I run this program by itself it seems to work (with it's own main, etc.), but when combined with my other program it doesn't.
This should be it's own independent thread should it not? Why would stuff going on in the other threads in my program affect this?
Any help is appreciated.. this is killing me.
thanks