新建测试Demo类执行定时任务
package com.task.zhixingshijian; import java.time.LocalDateTime; import java.time.temporal.ChronoField; import java.util.*; /** * @author wuzhenyong * ClassName:TaskDemo.java * date:2022-09-28 09:44 * Description: */ public class TaskDemo { /** * 指定时间执行一次定时任务 * * @param localDateTime 触发时机 * @param timing 参数信息 */ public void timing(LocalDateTime localDateTime, Map<String, String> timing) { Calendar calendar = Calendar.getInstance(); // 年份 calendar.set(Calendar.YEAR, localDateTime.get(ChronoField.YEAR)); // 月份 传入日期需要-1 calendar.set(Calendar.MONTH, localDateTime.get(ChronoField.MONTH_OF_YEAR)-1); // 天数 calendar.set(Calendar.DAY_OF_MONTH, localDateTime.get(ChronoField.DAY_OF_MONTH)); // 小时 calendar.set(Calendar.HOUR_OF_DAY, localDateTime.get(ChronoField.HOUR_OF_DAY)); // 分钟 calendar.set(Calendar.MINUTE, localDateTime.get(ChronoField.MINUTE_OF_HOUR)); // 秒 calendar.set(Calendar.SECOND, localDateTime.get(ChronoField.SECOND_OF_MINUTE)); Date time = calendar.getTime(); Timer timer = new Timer(); // 执行 timer.schedule(new TimerTask() { @Override public void run() { System.out.println("执行了指定执行时间任务,localDateTime:" + LocalDateTime.now()); System.out.println("执行内容:" + timing.toString()); } }, time); } }
创建项目启动后进行配置具体时间执行定时类
注意:此类只是测试一下,如果项目中是不需要此类的
package com.task.zhixingshijian; import org.springframework.stereotype.Component; import java.time.LocalDateTime; import java.util.HashMap; import java.util.Map; /** * @author wuzhenyong * ClassName:TaskCommandLineRunner.java * date:2022-09-28 09:43 * Description: */ @Component public class TaskCommandLineRunner implements org.springframework.boot.CommandLineRunner { /** * 启动项目后运行 * * @param args arg游 */ @Override public void run(String... args) { // 指定触发的时间1 LocalDateTime localDateTime1 = LocalDateTime.of(2022, 9, 28, 10, 14, 00); Map<String, String> timing1 = new HashMap<>(); timing1.put("name", "timing1"); new TaskDemo().timing(localDateTime1, timing1); // 指定触发的时间2 LocalDateTime localDateTime2 = LocalDateTime.of(2022, 9, 28, 10, 13, 00); Map<String, String> timing2 = new HashMap<>(); timing2.put("name", "timing2"); new TaskDemo().timing(localDateTime2, timing2); // 指定触发的时间3 LocalDateTime localDateTime3 = LocalDateTime.of(2022, 9, 28, 10, 15, 00); Map<String, String> timing3 = new HashMap<>(); timing3.put("name", "timing3"); new TaskDemo().timing(localDateTime3, timing3); } }
运行效果