您的位置:首页 > 其它

Quartz动态修改cronExpression的一种实现方式

2018-02-25 18:24 801 查看
1.采用注解的方式实现任务的扫描,在spring中要做如下配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd ">

<task:annotation-driven />


其中关键要配置的:

xmlns:context="http://www.springframework.org/schema/context" http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
<task:annotation-driven />


2.采用注解的方式

@Component
@EnableScheduling
public class updateCronTask implements SchedulingConfigurer {
@Autowired
private DqSurveyMapper dqSurveyMapper;
int i=0;

@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.addTriggerTask(new Runnable() {
@Override
public void run(){
i++;
// 业务逻辑都写在
System.out.println("第"+(i)+"次开始执行操作... " +"时间:【" + new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS").format(new Date()) + "】");

}
}, new Trigger(){
@Override
public Date nextExecutionTime(TriggerContext triggerContext) {
//任务触发,可修改任务的执行周期
CronTrigger trigger = new CronTrigger(getCron());
Date nextExec = trigger.nextExecutionTime(triggerContext);
return nextExec;
}
});
}
//此处这个方法可以改变cronExpression的表达式的值,默认的是5s扫描一次,当数据库中有匹配的记录时,就按数据库中配置好的cronExpression来执行任务,可以动态的修改数据库中的表达式
public String getCron(){
String core="0/5 * * * * ?";
boolean flag = false;
BigDecimal idtest=null;
List<BigDecimal> list = dqSurveyMapper.getAllId();
for(int j=0;j<list.size();j++){
BigDecimal id = list.get(j);
if(id.longValue()==6787821575400900L){
idtest = id;
flag = true;
}
}
if(flag){
DqSurvey dqSurvey = dqSurveyMapper.selectByPrimaryKey(idtest);
return dqSurvey.getSurveyTilte();
}else{
return core;
}
}
}


上述方法是去扫描的数据库,也可以通过Controller层传表达式过来

3.cronExpression表达式的在线生成

http://cron.qqe2.com/


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐