Java 定时任务:早上9点到下午4点执行9次
要实现早上9点到下午4点执行9次的定时任务,可以使用Java中的ScheduledExecutorService类来实现。
首先,需要创建一个ScheduledExecutorService对象,并设置线程池的大小:
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10);
接下来,可以使用scheduledExecutorService.scheduleAtFixedRate()方法来定时执行任务。该方法的参数包括:
- Runnable对象,表示要执行的任务;
- 首次执行的延迟时间,以时间单位表示;
- 两次执行之间的间隔时间,以时间单位表示。
为了实现每天早上9点到下午4点执行9次的定时任务,可以设置首次执行的延迟时间为当前时间到下一个9点的时间差,间隔时间为每天的时间间隔除以9。
具体实现代码如下:
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10);
// 计算当前时间到下一个9点的时间差
Calendar now = Calendar.getInstance();
Calendar next9am = Calendar.getInstance();
next9am.set(Calendar.HOUR_OF_DAY, 9);
next9am.set(Calendar.MINUTE, 0);
next9am.set(Calendar.SECOND, 0);
if (now.after(next9am)) {
next9am.add(Calendar.DAY_OF_MONTH, 1);
}
long initialDelay = next9am.getTimeInMillis() - now.getTimeInMillis();
// 计算每次执行的间隔时间
long period = (16 - 9) * 60 * 60 * 1000 / 9;
// 执行任务
scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
int count = 0;
@Override
public void run() {
if (count < 9) {
// 执行任务
// ...
count++;
} else {
scheduledExecutorService.shutdown();
}
}
}, initialDelay, period, TimeUnit.MILLISECONDS);
在上述代码中,首先计算当前时间到下一个9点的时间差,然后计算每次执行的间隔时间。最后使用scheduleAtFixedRate()方法执行任务,当执行次数达到9次时,调用scheduledExecutorService.shutdown()方法停止定时任务。
原文地址: https://www.cveoy.top/t/topic/m3Li 著作权归作者所有。请勿转载和采集!