1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
| public class Main {
static LocalDateTime nextTime;
static long time;
public static void main(String[] args) {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
time = 0L;
nextTime = LocalDateTime.now(); System.out.println("当前时间:"+nextTime);
String cron = "9:0:0,3:0:0,90"; TrSchedule trSchedule = new TrSchedule(cron);
for(int i=0;i<30;i++){
System.out.println(""); long m = getLastNextTimeM(nextTime,trSchedule); time = (time==0L)?System.currentTimeMillis()+(m*60*1000):time+(m*60*1000); System.out.println("开始第"+i+"周期任务还需"+m+"分钟(执行时间:"+dateFormat.format(new Date(time))+")"); System.out.println("");
} }
public static long getLastNextTimeM(LocalDateTime currentDate,TrSchedule trSchedule){ LocalDateTime startDate = trSchedule.getStartDate().withDayOfMonth(currentDate.getDayOfMonth()).withDayOfYear(currentDate.getDayOfYear()); LocalDateTime endDate = trSchedule.getEndDate().withDayOfMonth(currentDate.getDayOfMonth()).withDayOfYear(currentDate.getDayOfYear());
if(endDate.isBefore(startDate)) endDate = endDate.plusDays(1);
if(currentDate.isAfter(endDate)){ nextTime = startDate.plusDays(1).plusMinutes(trSchedule.getDelay()); return getLast(currentDate,startDate.getHour(),startDate.getMinute(),startDate.getSecond())+trSchedule.getDelay(); } if(currentDate.isBefore(startDate)){ long rm = getLast(currentDate,startDate.getHour(),startDate.getMinute(),startDate.getSecond())+trSchedule.getDelay(); nextTime = currentDate.plusMinutes(rm); return rm; }else if(currentDate.isAfter(startDate)){ if(currentDate.plusMinutes(trSchedule.getDelay()).isAfter(endDate)){ long rm = getLast(currentDate,startDate.getHour(),startDate.getMinute(),startDate.getSecond())+trSchedule.getDelay(); nextTime = currentDate.plusMinutes(rm); return rm; } nextTime = currentDate.plusMinutes(trSchedule.getDelay()); return trSchedule.getDelay(); } return -1; }
public static long getLast(LocalDateTime currentTime,int hour, int minute,int s) { LocalDateTime time = LocalDateTime.now(); time = time.withHour(hour); time = time.withMinute(minute); time = time.withSecond(0); time = time.withDayOfMonth(currentTime.getDayOfMonth()); time = time.withDayOfYear(currentTime.getDayOfYear()); if (time.isBefore(currentTime)) time = time.plusDays(1L); long re = time.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); return (re - currentTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()) / 1000L/60L; } }
|