定时任务每天2点12点下午5点执行
时间: 2024-06-14 20:07:02 浏览: 135
以下是Java中定时任务每天2点、12点和下午5点执行的示例代码:
```java
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class TimerManager {
public static void main(String[] args) {
Timer timer = new Timer();
// 设置每天2点执行任务
Calendar calendar1 = Calendar.getInstance();
calendar1.set(Calendar.HOUR_OF_DAY, 2);
calendar1.set(Calendar.MINUTE, 0);
calendar1.set(Calendar.SECOND, 0);
Date date1 = calendar1.getTime();
if (date1.before(new Date())) {
date1 = addDay(date1, 1);
}
timer.schedule(new TimerTask() {
@Override
public void run() {
// 执行任务的代码
System.out.println("任务1:每天2点执行");
}
}, date1, 24 * 60 * 60 * 1000);
// 设置每天12点执行任务
Calendar calendar2 = Calendar.getInstance();
calendar2.set(Calendar.HOUR_OF_DAY, 12);
calendar2.set(Calendar.MINUTE, 0);
calendar2.set(Calendar.SECOND, 0);
Date date2 = calendar2.getTime();
if (date2.before(new Date())) {
date2 = addDay(date2, 1);
}
timer.schedule(new TimerTask() {
@Override
public void run() {
// 执行任务的代码
System.out.println("任务2:每天12点执行");
}
}, date2, 24 * 60 * 60 * 1000);
// 设置每天下午5点执行任务
Calendar calendar3 = Calendar.getInstance();
calendar3.set(Calendar.HOUR_OF_DAY, 17);
calendar3.set(Calendar.MINUTE, 0);
calendar3.set(Calendar.SECOND, 0);
Date date3 = calendar3.getTime();
if (date3.before(new Date())) {
date3 = addDay(date3, 1);
}
timer.schedule(new TimerTask() {
@Override
public void run() {
// 执行任务的代码
System.out.println("任务3:每天下午5点执行");
}
}, date3, 24 * 60 * 60 * 1000);
}
// 增加一天
private static Date addDay(Date date, int num) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, num);
return calendar.getTime();
}
}
```
阅读全文