java scheduled 每月最后一天
时间: 2023-09-16 17:14:53 浏览: 48
可以使用 Java 的 ScheduledExecutorService 结合 Calendar 类来实现每月最后一天的定时任务。以下是示例代码:
```
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 LastDayOfMonthTask {
public static void main(String[] args) {
// 创建 ScheduledExecutorService
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
// 获取当前时间
Calendar now = Calendar.getInstance();
int currentMonth = now.get(Calendar.MONTH);
// 计算下个月的最后一天
int nextMonth = (currentMonth + 1) % 12;
now.set(Calendar.MONTH, nextMonth);
int lastDay = now.getActualMaximum(Calendar.DAY_OF_MONTH);
// 计算定时任务执行的时间
now.set(Calendar.DAY_OF_MONTH, lastDay);
now.set(Calendar.HOUR_OF_DAY, 0);
now.set(Calendar.MINUTE, 0);
now.set(Calendar.SECOND, 0);
Date scheduledTime = now.getTime();
// 执行定时任务
executor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
// TODO: 在这里编写每个月最后一天要执行的任务
}
}, scheduledTime.getTime() - System.currentTimeMillis(), TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS), TimeUnit.MILLISECONDS);
}
}
```
这段代码会计算下个月的最后一天,并且在该天凌晨执行定时任务。你可以在 `Runnable` 的 `run` 方法中编写每个月最后一天要执行的任务。