5

I want to trigger a Java code at specific timing, let say every morning 1 AM.

I write a thread as below:

while (true) {
    if (currentTime = 1AM) {
        doSomething;
    }       
}

I am a bit worry, the while loop keep running, will it slow down the machine, or eating up processing resource?

My first question is, I am thinking if I only loop 1 time per second, will it better?

while (true) {
    if (currentTime = 1AM) {
        doSomething;
    }       

    Thread.sleep(1000);
}

My second question is, some time I see while loop written as below, most of time to acquire the Java lock, can anyone explain how expensive if we write the while loop like below (sorry if this is very basic question)?

while (isLock) {
    // do nothing
}

doThisIfNoLock();

I extend the thought above, if I create a empty thread, and an infinite empty while loop inside, how many resource (processing power) that actually eating up by the thread? Because there is no content inside the loop, based on my imagination, the loop will be running very fast, and end up taking many cycles of CPU power? Is that true?

Raedwald
  • 46,613
  • 43
  • 151
  • 237
Sam YC
  • 10,725
  • 19
  • 102
  • 158
  • There are schedulers to do such things. Look at Quartz Scheduler. If you are using Spring, you can schedule such things. Your approach is bad – TheLostMind Jul 29 '16 at 06:05
  • Even `java.util.Timer` is better than what you are attempting. – Mad Physicist Jul 29 '16 at 06:06
  • You can not run infinite while loop.. It will suck the resources and slow down the processing. Use schedulers instead. – Rish Jul 29 '16 at 06:06
  • 1
    http://stackoverflow.com/questions/9375882/how-i-can-run-my-timertask-everyday-2-pm – Lijo Jul 29 '16 at 06:07

2 Answers2

5

Its not a good practice to run a infinite while loop as it can hog the CPU.

For Scheduled tasks you can use either libraries like Quartz or use java.util.Timer and java.util.TimerTask

Your Task needs to inherit from TimerTask and override the run() method. And then you need to use Time.schedule() method to schedule your task.

Yogesh_D
  • 17,656
  • 10
  • 41
  • 55
2

Thread.sleep can be used in this scenario however a better option would be using a timer similar to this

long current = System.currentTimeMillis();   
while(current < expectedElapsedTime){
    current = System.currentTimeMillis();
    //logic goes here
} 

Running a infinite loop without some sort of timer to slow the loop down will suck all your resources out of your computer like a vacuum. Another way you can schedule tasks is with a swing timer

ActionListener listener = new ActionListener(){
public void actionPerformed(ActionEvent event){
    checkUser = true;
  }
};
Timer checkUserTimer = new Timer(5000, listener); // 5 second pause
checkUserTimer.start(); // start the timer.
Ryan
  • 1,972
  • 2
  • 23
  • 36