Schedule monthly task using ScheduledExecutorService(使用ScheduledExecutorService计划每月任务)
本文介绍了使用ScheduledExecutorService计划每月任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要将任务安排在每月的特定日期和特定时间。每次运行之间的间隔可以设置为1到12个月。在Java中,可以使用ScheduledExecutorService以固定的时间间隔调度任务。由于一个月的天数不是固定的,如何实现这一点?
提前感谢。
推荐答案
如果您在JavaEE环境中运行,则应该使用TimerService或@Schedule注释。但是,由于您讨论的是ScheduledExecutorService,它不允许在Java EE容器中使用,所以我假定您没有在容器中运行。
使用ScheduledExecutorService时,您可以让任务本身计划下一次迭代:
final ScheduledExecutorService executor = /* ... */ ;
Runnable task = new Runnable() {
@Override
public void run() {
ZonedDateTime now = ZonedDateTime.now();
long delay = now.until(now.plusMonths(1), ChronoUnit.MILLIS);
try {
// ...
} finally {
executor.schedule(this, delay, TimeUnit.MILLISECONDS);
}
}
};
int dayOfMonth = 5;
ZonedDateTime dateTime = ZonedDateTime.now();
if (dateTime.getDayOfMonth() >= dayOfMonth) {
dateTime = dateTime.plusMonths(1);
}
dateTime = dateTime.withDayOfMonth(dayOfMonth);
executor.schedule(task,
ZonedDateTime.now().until(dateTime, ChronoUnit.MILLIS),
TimeUnit.MILLISECONDS);
在早于8的Java版本中,您可以使用日历执行相同的操作:
final ScheduledExecutorService executor = /* ... */ ;
Runnable task = new Runnable() {
@Override
public void run() {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, 1);
long delay =
calendar.getTimeInMillis() - System.currentTimeMillis();
try {
// ...
} finally {
executor.schedule(this, delay, TimeUnit.MILLISECONDS);
}
}
};
int dayOfMonth = 5;
Calendar calendar = Calendar.getInstance();
if (calendar.get(Calendar.DAY_OF_MONTH) >= dayOfMonth) {
calendar.add(Calendar.MONTH, 1);
}
calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
executor.schedule(task,
calendar.getTimeInMillis() - System.currentTimeMillis(),
TimeUnit.MILLISECONDS);
这篇关于使用ScheduledExecutorService计划每月任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
织梦狗教程
本文标题为:使用ScheduledExecutorService计划每月任务
基础教程推荐
猜你喜欢
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
