Springboot动态时间定时器

235 阅读1分钟

package com.cdzg.labormatrix.schedule;

import com.cdzg.labormatrix.mapper.news.NewsMapper; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.scheduling.Trigger; import org.springframework.scheduling.TriggerContext; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import org.springframework.scheduling.support.CronTrigger; import org.springframework.stereotype.Component;

import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ScheduledFuture;

/**

  • Created with IntelliJ IDEA

  • @ClassName UserSmsSendTwoTask

  • @Function TODO

  • @Description

  • @Author Lgs

  • @Date 2020/5/6 12:58 */ @Component @EnableScheduling @Slf4j public class CmsScheduleTask {

    @Autowired private ThreadPoolTaskScheduler threadPoolTaskScheduler;

    @Autowired private NewsMapper newsMapper;

    private ScheduledFuture<?> future;

    private int taskSchedulerCorePoolSize = 50;

    static boolean isinitialized = false;

    @Bean public ThreadPoolTaskScheduler threadPoolTaskScheduler() { threadPoolTaskScheduler = new ThreadPoolTaskScheduler(); threadPoolTaskScheduler.setPoolSize(taskSchedulerCorePoolSize); //需要实例化线程 threadPoolTaskScheduler.initialize(); isinitialized = true; return threadPoolTaskScheduler; }

    private String cron = "";

    public String getCron() { return cron; }

    /**

    • 开启定时任务

    • @param cron

    • @param id */ public void setCron(String cron, Long id) { this.cron = cron; stopCron(); future = threadPoolTaskScheduler.schedule(() -> { try { log.info("定时发送资讯:" + cron); newsMapper.updateStatusById(id); } catch (Exception e) { e.printStackTrace(); } }, triggerContext -> { if (StringUtils.isEmpty(cron)){ return null; } Date date = new CronTrigger(cron).nextExecutionTime(triggerContext); return date;

       });
      

    }

    /**

    • 取消任务调度 */ public void stopCron() { if (future != null) { future.cancel(true); } }

}