@Scheduled
@Component
public class zhy{
@Resource
private Zhy zhy;
/**
* 每分钟更新
*/
@Scheduled(cron = "0 0/1 * * * ?")
public void initTask() {
System.out.println("每分钟更新一次");
}
}
public class ZhyConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
scheduledTaskRegistrar.addTriggerTask(
//1.添加任务内容(Runnable)
() -> System.out.println("执行定时任务2: " + LocalDateTime.now().toLocalTime()),
//2.设置执行周期(Trigger)
triggerContext -> {
//2.1 从数据库获取执行周期
String cron = zhyMapper.getCron();
//2.2 合法性校验.
if (StringUtils.isEmpty(cron)) {
// Omitted Code ..
}
//2.3 返回执行周期(Date)
return new CronTrigger(cron).nextExecutionTime(triggerContext);
}
);
}
}
此方式可以从数据库中配置执行,但是需要每次到定时执行的时候才会更新读取最新的配置
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author zhy
* @date 2019/2/28 14:07
*/
public class BeanUtils {
public static Field findField(Class> clazz, String name) {
try {
return clazz.getField(name);
} catch (NoSuchFieldException ex) {
return findDeclaredField(clazz, name);
}
}
public static Field findDeclaredField(Class> clazz, String name) {
try {
return clazz.getDeclaredField(name);
} catch (NoSuchFieldException ex) {
if (clazz.getSuperclass() != null) {
return findDeclaredField(clazz.getSuperclass(), name);
}
return null;
}
}
public static Method findMethod(Class> clazz, String methodName, Class>... paramTypes) {
try {
return clazz.getMethod(methodName, paramTypes);
} catch (NoSuchMethodException ex) {
return findDeclaredMethod(clazz, methodName, paramTypes);
}
}
public static Method findDeclaredMethod(Class> clazz, String methodName, Class>... paramTypes) {
try {
return clazz.getDeclaredMethod(methodName, paramTypes);
} catch (NoSuchMethodException ex) {
if (clazz.getSuperclass() != null) {
return findDeclaredMethod(clazz.getSuperclass(), methodName, paramTypes);
}
return null;
}
}
public static Object getProperty(Object obj, String name) throws NoSuchFieldException {
Object value = null;
Field field = findField(obj.getClass(), name);
if (field == null) {
throw new NoSuchFieldException("no such field [" + name + "]");
}
boolean accessible = field.isAccessible();
field.setAccessible(true);
try {
value = field.get(obj);
} catch (Exception e) {
throw new RuntimeException(e);
}
field.setAccessible(accessible);
return value;
}
public static void setProperty(Object obj, String name, Object value) throws NoSuchFieldException {
Field field = findField(obj.getClass(), name);
if (field == null) {
throw new NoSuchFieldException("no such field [" + name + "]");
}
boolean accessible = field.isAccessible();
field.setAccessible(true);
try {
field.set(obj, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
field.setAccessible(accessible);
}
public static Map obj2Map(Object obj, Map map) {
if (map == null) {
map = new HashMap<>();
}
if (obj != null) {
try {
Class> clazz = obj.getClass();
do {
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
int mod = field.getModifiers();
if (Modifier.isStatic(mod)) {
continue;
}
boolean accessible = field.isAccessible();
field.setAccessible(true);
map.put(field.getName(), field.get(obj));
field.setAccessible(accessible);
}
clazz = clazz.getSuperclass();
} while (clazz != null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return map;
}
/**
* 获得父类集合,包含当前class
*
* @param clazz
* @return
*/
public static List> getSuperclassList(Class> clazz) {
List> clazzes = new ArrayList<>(3);
clazzes.add(clazz);
clazz = clazz.getSuperclass();
while (clazz != null) {
clazzes.add(clazz);
clazz = clazz.getSuperclass();
}
return Collections.unmodifiableList(clazzes);
}
}
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.SchedulingException;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.config.TriggerTask;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
/**
* @author zhy
* @date 2019/2/28 14:04
*/
@Configuration
@EnableScheduling
public class DefaultSchedulingConfigurer implements SchedulingConfigurer {
private ScheduledTaskRegistrar taskRegistrar;
private Set> scheduledFutures = null;
private Map> taskFutures = new ConcurrentHashMap<>();
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
this.taskRegistrar = taskRegistrar;
}
@SuppressWarnings("unchecked")
private Set> getScheduledFutures() {
if (scheduledFutures == null) {
try {
// spring版本不同选用不同字段scheduledFutures
scheduledFutures = (Set>) BeanUtils.getProperty(taskRegistrar, "scheduledTasks");
} catch (NoSuchFieldException e) {
throw new SchedulingException("not found scheduledFutures field.");
}
}
return scheduledFutures;
}
/**
* 添加任务
*/
public void addTriggerTask(String taskId, TriggerTask triggerTask) {
if (taskFutures.containsKey(taskId)) {
throw new SchedulingException("the taskId[" + taskId + "] was added.");
}
TaskScheduler scheduler = taskRegistrar.getScheduler();
ScheduledFuture> future = scheduler.schedule(triggerTask.getRunnable(), triggerTask.getTrigger());
getScheduledFutures().add(future);
taskFutures.put(taskId, future);
}
/**
* 取消任务
*/
public void cancelTriggerTask(String taskId) {
ScheduledFuture> future = taskFutures.get(taskId);
if (future != null) {
future.cancel(true);
}
taskFutures.remove(taskId);
getScheduledFutures().remove(future);
}
/**
* 重置任务
*/
public void resetTriggerTask(String taskId, TriggerTask triggerTask) {
cancelTriggerTask(taskId);
addTriggerTask(taskId, triggerTask);
}
/**
* 任务编号
*/
public Set taskIds() {
return taskFutures.keySet();
}
/**
* 是否存在任务
*/
public boolean hasTask(String taskId) {
return this.taskFutures.containsKey(taskId);
}
/**
* 任务调度是否已经初始化完成
*/
public boolean inited() {
return this.taskRegistrar != null && this.taskRegistrar.getScheduler() != null;
}
}
测试使用
@Resource
private DefaultSchedulingConfigurer defaultSchedulingConfigurer;
@GetMapping("zhy")
public void zhy() throws InterruptedException {
while (!defaultSchedulingConfigurer.inited())
{
Thread.sleep(100);
}
defaultSchedulingConfigurer.addTriggerTask("task",
new TriggerTask(
() -> System.out.println("zhyzhy"),
new CronTrigger("0/5 * * * * ? ")));
}
@GetMapping("uzhy")
public void uzhy(){
defaultSchedulingConfigurer.cancelTriggerTask("task");
}