mirror of
https://gitee.com/chinabugotech/hutool.git
synced 2025-07-21 15:09:48 +08:00
fix cron bug
This commit is contained in:
@@ -44,16 +44,18 @@ public class CronTimer extends Thread implements Serializable {
|
||||
long sleep;
|
||||
while(false == isStop){
|
||||
//下一时间计算是按照上一个执行点开始时间计算的
|
||||
//此处除以定时单位是为了清零单位以下部分,例如单位是分则秒和毫秒清零
|
||||
nextTime = ((thisTime / timerUnit) + 1) * timerUnit;
|
||||
sleep = nextTime - System.currentTimeMillis();
|
||||
if (sleep > 0 && false == ThreadUtil.safeSleep(sleep)) {
|
||||
//等待直到下一个时间点,如果被中断直接退出Timer
|
||||
break;
|
||||
if(isValidSleepMillis(sleep, timerUnit)){
|
||||
if (false == ThreadUtil.safeSleep(sleep)) {
|
||||
//等待直到下一个时间点,如果被中断直接退出Timer
|
||||
break;
|
||||
}
|
||||
//执行点,时间记录为执行开始的时间,而非结束时间
|
||||
thisTime = System.currentTimeMillis();
|
||||
spawnLauncher(thisTime);
|
||||
}
|
||||
|
||||
//执行点,时间记录为执行开始的时间,而非结束时间
|
||||
thisTime = System.currentTimeMillis();
|
||||
spawnLauncher(thisTime);
|
||||
}
|
||||
log.debug("Hutool-cron timer stoped.");
|
||||
}
|
||||
@@ -73,4 +75,22 @@ public class CronTimer extends Thread implements Serializable {
|
||||
private void spawnLauncher(final long millis){
|
||||
this.scheduler.taskLauncherManager.spawnLauncher(millis);
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查是否为有效的sleep毫秒数,包括:
|
||||
* <pre>
|
||||
* 1. 是否>0,防止用户向未来调整时间
|
||||
* 1. 是否<两倍的间隔单位,防止用户向历史调整时间
|
||||
* </pre>
|
||||
*
|
||||
* @param millis 毫秒数
|
||||
* @param timerUnit 定时单位,为秒或者分的毫秒值
|
||||
* @return 是否为有效的sleep毫秒数
|
||||
* @since 5.3.2
|
||||
*/
|
||||
private static boolean isValidSleepMillis(long millis, long timerUnit){
|
||||
return millis > 0 &&
|
||||
// 防止用户向前调整时间导致的长时间sleep
|
||||
millis < (2 * timerUnit);
|
||||
}
|
||||
}
|
||||
|
@@ -36,13 +36,14 @@ public class CronTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore
|
||||
// @Ignore
|
||||
public void cronTest2() {
|
||||
// 支持秒级别定时任务
|
||||
CronUtil.setMatchSecond(true);
|
||||
CronUtil.start();
|
||||
|
||||
ThreadUtil.sleep(30000);
|
||||
|
||||
ThreadUtil.waitForDie();
|
||||
Console.log("Exit.");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
Reference in New Issue
Block a user