boot中的Scheduling定時器使用筆記

使用@Scheduled(類上或者啓動類上必須加上@EnableScheduling,且是單線程

 @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

  1. 使用註解@EnableAsync@Async
  2. 建立線程池
@Configurable
public class ScheduleConfig {

    @Bean
    public TaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(10);
        return scheduler;
    }
}

 

實現SchedulingConfigurer接口(並行線程

@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);
                }
        );
    }
}

cron表達式

 不會,通常直接到生成器網站 http://www.bejson.com/othertools/cron/多線程

相關文章
相關標籤/搜索