本文介绍了使用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计划每月任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-19 07:57