spring建立动态定时任务
1. 创建定时器抽象类
/**
* 定时器抽象类
*
* @author
*
*/
public abstract class ScheduleTask implements Runnable {
private String id;
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public ScheduleTask(String id) {
this.id = id;
}
@Override
public abstract void run();
}
2.写定时任务工具类
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;
import www.wensi.com.vmi.task.ScheduleTask;
/**
* 定时任务工具类
*
*/
@Slf4j
@Component
public class ScheduleUtil {
private static ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
private static Map<String, ScheduledFuture<?>> scheduledFutureMap = new HashMap<>();
static {
threadPoolTaskScheduler.initialize();
log.debug("初始化线程池...");
}
/**
* 启动某定时任务,到时间点就运行一次
*
* @param scheduleTask
* @param startTime
*/
public void start(ScheduleTask scheduleTask, Date startTime) {
if (isExist(scheduleTask.getId())) {
log.debug("启动定时任务" + scheduleTask.getId() + "失败,任务已存在");
return;
}
ScheduledFuture<?> scheduledFuture = threadPoolTaskScheduler.schedule(scheduleTask, startTime);
scheduledFutureMap.put(scheduleTask.getId(), scheduledFuture);
log.debug("启动定时任务" + scheduleTask.getId() +