spring task 基於接口的動態定時任務


 

基於接口(SchedulingConfigurer)

 

@Configuration
@EnableScheduling
public class DynamicScheduleTask implements SchedulingConfigurer {

    /**
     * 動態 執行定時任務.
     */
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {

        List<Map<String, String>> mapList = new ArrayList<>();
        {
            Map<String, String> map = new HashMap<>();
            map.put("id", "1");
            map.put("cron", "0/5 * * * * ?");
            mapList.add(map);
        }
        {
            Map<String, String> map2 = new HashMap<>();
            map2.put("id", "2");
            map2.put("cron", "0/6 * * * * ?");
            mapList.add(map2);
        }
        for (Map<String, String> stringMap : mapList) {
            String id = stringMap.get("id");
            String cron = stringMap.get("cron");

            taskRegistrar.addTriggerTask(
                    //添加任務內容(Runnable)
 () -> System.out.println("執行動態定時任務: " + LocalDateTime.now().toLocalTime()),
            //設置執行周期(Trigger) triggerContext -> { //2.1 從數據庫獲取執行周期 // TODO //2.2 合法性校驗. if (StringUtils.isEmpty(cron)) { // Omitted Code .. } //2.3 返回執行周期(Date) return new CronTrigger(cron).nextExecutionTime(triggerContext); } ); } } }

 

參考文章:https://blog.csdn.net/u013987258/article/details/106671908

源碼:https://gitee.com/caoyeoo0/xc-springboot/tree/springTask/

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM