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/m3La 著作权归作者所有。请勿转载和采集!