Java早上9点到下午4点执行7次的定时任务
可以使用Java中的ScheduledExecutorService来实现定时任务的执行。下面是一个例子,该定时任务会在每天的早上9点到下午4点之间,每隔一个小时执行一次,共执行7次。
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ScheduledTaskExample {
public static void main(String[] args) {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
int delay = getDelay();
for (int i = 0; i < 7; i++) {
executor.schedule(new Task(), delay, TimeUnit.SECONDS);
delay += 3600; // 每隔一个小时执行一次
}
}
private static int getDelay() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 9);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
Date nineAM = cal.getTime();
cal.set(Calendar.HOUR_OF_DAY, 16);
Date fourPM = cal.getTime();
Date now = new Date();
if (now.before(nineAM)) {
return (int) ((nineAM.getTime() - now.getTime()) / 1000);
} else if (now.after(fourPM)) {
cal.add(Calendar.DAY_OF_MONTH, 1);
nineAM = cal.getTime();
return (int) ((nineAM.getTime() - now.getTime()) / 1000);
} else {
return 0;
}
}
private static class Task implements Runnable {
public void run() {
System.out.println("Executing task at " + new Date());
}
}
}
在该例子中,我们首先创建了一个ScheduledExecutorService实例,并设置了线程池大小为1。
然后,我们使用getDelay()方法来计算第一次任务执行的延迟时间。该方法会根据当前时间和每天的9点和4点来计算,如果当前时间在9点之前,则第一次任务会在9点执行;如果当前时间在4点之后,则第一次任务会在明天的9点执行;否则第一次任务会立即执行。
接着,我们使用一个循环来执行7次任务。在每次循环中,我们使用executor.schedule()方法来安排任务的执行,并将延迟时间设置为上一次执行时间加上一个小时。
最后,我们定义了一个Task类,该类实现了Runnable接口,用来执行具体的任务。在该例子中,我们只是简单地输出了一条日志。
注意,在实际应用中,我们应该使用try-catch语句来捕获可能抛出的异常,如InterruptedException等。同时,我们也应该在程序结束时调用executor.shutdown()方法来关闭线程池。
原文地址: https://www.cveoy.top/t/topic/bzIp 著作权归作者所有。请勿转载和采集!