目录
- 1.java定时器原生方法
1.java定时器原生方法
实现每天早上8点执行任务的示例代码
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;public class TimeTest{public static void main(String[] args) {ScheduledExecutorService timer = new ScheduledThreadPoolExecutor(1);MyTask task1 = new MyTask();// 获取当前时间Calendar now = Calendar.getInstance();// 设置每天早上8点执行Calendar scheduleTime = Calendar.getInstance();scheduleTime.set(Calendar.HOUR_OF_DAY, 8);scheduleTime.set(Calendar.MINUTE, 0);scheduleTime.set(Calendar.SECOND, 0);// 如果当前时间已经超过了今天的8点,则修改为明天的8点if (now.after(scheduleTime)) {scheduleTime.add(Calendar.DATE, 1);}// 计算初始延迟时间long initialDelay = scheduleTime.getTimeInMillis() - now.getTimeInMillis();timer.scheduleAtFixedRate(task1, initialDelay,24 * 60 * 60 * 1000, TimeUnit.SECONDS);}public static class MyTask implements Runnable {@Overridepublic void run() {//执行的业务逻辑System.out.println("执行的业务逻辑.......");}}
}