@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/多線程