@Scheduled(cron = "0/2 * * * * *") public void timerBreakCat(){ LocalDateTime localDateTime = LocalDateTime.now(); System.out.println("Cat当前时间为:" + localDateTime.format(DateTimeFormatter.ofPattern("MM-dd HH:mm:ss"))); } @Scheduled(cron = "0/2 * * * * *") public void timerBreakDog(){ LocalDateTime localDateTime = LocalDateTime.now(); System.out.println("Dog当前时间为:" + localDateTime.format(DateTimeFormatter.ofPattern("MM-dd HH:mm:ss"))); }
改成多线程的俩种比较简单方式json
@Configurable public class ScheduleConfig { @Bean public TaskScheduler taskScheduler() { ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler(); scheduler.setPoolSize(10); return scheduler; } }
@Configuration @Slf4j public class DemoTask implements SchedulingConfigurer { private static String cron = "0/5 * * * * ?"; @Async @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { taskRegistrar.addTriggerTask( //1.添加任务内容(Runnable) () -> new Thread(() -> { try { // TODO 任务内容 log.info("执行时间:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); } catch (Exception e) { e.printStackTrace(); } }).start(), //2.设置执行周期(Trigger) triggerContext -> { //随机生成cron String temp = ((int) (Math.random() * 7+3))+""; cron = "0/"+temp+" * * * * ?"; //返回执行周期(Date) return new CronTrigger(cron).nextExecutionTime(triggerContext); } ); } }
不会,通常直接到生成器网站 http://www.bejson.com/othertools/cron/多线程