上一集 我们扯到了 调用WebService接口,并且成功拿到了接口返回和JavaBean。
https://blog.csdn.net/weixin_44458365/article/details/106993689
这一集我们说关于定时任务的配置创建。
先说说我们的定时任务。
项目需求:
1、接口需要提供给前端。
2、前端页面可以配置定时任务的启停。
3、前端页面可以配置定时任务的执行频率。
1、在启动器上加注解
@EnableScheduling
2、编写代码
package up.tour.link.task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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 up.tour.link.service.ShtourService;
import up.tour.link.service.TestService;
import javax.xml.bind.JAXBException;
import javax.xml.soap.SOAPException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Date;
import java.util.concurrent.ScheduledFuture;
@Component
public class ScheduleConfig {
@Autowired
private ThreadPoolTaskScheduler threadPoolTaskScheduler;
@Bean
public ThreadPoolTaskScheduler threadPoolTaskScheduler(){
return new ThreadPoolTaskScheduler();
}
private String cron = "";
@Autowired
private ShtourService shtourService;
private ScheduledFuture<?>future;
public void stopCron(){
if(future !=null){
future.cancel(true);
}
}
public String getCron() {
return cron;
}
public void setCron(String cron) {
this.cron = cron;
stopCron();
future = threadPoolTaskScheduler.schedule(new Runnable() {
@Override
public void run() {
try {
shtourService.dataStoreAndFiltering();
} catch (IOException e) {
e.printStackTrace();
} catch (JAXBException e) {
e.printStackTrace();
} catch (SOAPException e) {
e.printStackTrace();
}
}
}, new Trigger() {
@Override
public Date nextExecutionTime(TriggerContext triggerContext) {
if ("".equals(cron) || cron == null) {
return null;
}
CronTrigger cronTrigger = new CronTrigger(cron);
return cronTrigger.nextExecutionTime(triggerContext);
}
});
}
}
3、在控制器中(Controller)注入
4、定时任务的开启
@RequestMapping(value = "/startScheduleByCron")
public String getOpenSechedule(HttpServletRequest request){
String cron = request.getParameter("cron");
if(StringUtils.isEmpty(cron)){
log.info("启动失败");
return null;
}
scheduleConfig.setCron(cron);
log.info("启动成功");
return "伪代码";
}
5、定时任务的关闭
@RequestMapping(value = "/closeScheduleTask")
public String closeScheduleTask(HttpServletRequest request){
try {
scheduleConfig.stopCron();
log.info("启动成功");
} catch (Exception e) {
e.printStackTrace();
log.info("启动失败");
}
return "伪代码";
}
写到这里 关于动态定时任务的启停就完成了。
再见!!!
有没有想看续集的!!!
续集调用WebService接口(四)