문제

while(true){
    try 
    {
        if(Calendar.DATE == X){
            startTask();
        } 
        long delay = timeUntilNextCheck();
        Thread.sleep(delay);
    } 
    catch (Throwable t) 
    {

    }
}

I have a program that requires a specific task to run on a specific day of the month. After the task is run (Or if its not that day) the thread sleeps until tomorrow where it will check again.

However, I am getting a Dead code warning because part of the code is only ran on a specific day of the month.

I had a read up on what this warning is and I found that in some cases the compiler doesn't compile dead code. So my question is, will this always be compiled?

도움이 되었습니까?

해결책

However, I am getting a Dead code warning because part of the code is only ran on a specific day of the month.

No, you're getting a dead code warning becase startTask(); will never run. Calendar.DATE is an internal index constant of the Calendar class with the value 5. To get the current day of the month, use this code: Calendar.getInstance().get(Calendar.DAY_OF_MONTH)

다른 팁

Can you tell us what X is?

if(Calendar.DATE == X)

If X is some constant representing day of month, this will not work because you are comparing Calendar.DATE constant with another constant X. Let me guess, your code is something like:

if(Calendar.DATE == 17)  //run on 17th of every month

which translates into:

if(5 == 17)  //I see dead code

Compiler gives you a hint that this condition will never be satisfied (and might not bother compiling the if statement body).

Instead you should test:

if(new GregorianCalendar().get(Calendar.DATE) == 17)

Or even better use Quartz. You would be surprised how many mistakes can you make with such a simple code (think: server timezone, daylight saving time...)

I presume the dead code is the line startTask();

If the compiler can detect that this is unreachable, it is probably because X (whatever it is) can never take the same value as Calendar.DATE, which is always 5. This is "field number for get and set indicating the day of the month." according to the Javadoc, not the current day of the month, which you could get for example using

Calendar.getInstance().get(Calendar.DATE)

You might want to look at something like java.util.Timer by the way.

Go for quartz and configure CronTrigger that would be far better

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top