1. 编写定时任务(在任务方法run()中使用service查询数据库),任务类需要实现Runnable接口
public class SchedulerTask implements Runnable{
/**
* DESC : 定时任务逻辑
*
* */
@Override
public void run() {
System.out.println("Schedule............");
}
}
2.编写开启/设置定时时间、关闭定时任务接口
@Controller
public class TaskController {
@Autowired
private ThreadPoolTaskScheduler threadPoolTaskScheduler;
private ScheduledFuture<?> future;
@RequestMapping(value = "/startTask.do", method = RequestMethod.POST)
@ResponseBody
public String startTask(String time) throws UnsupportedEncodingException {
stopTask(); //先关闭之前的定时任务
String cron = "*/5 * * * * ?"; //定时任务时间表达式
//开启定时任务
future = threadPoolTaskScheduler.schedule(new SchedulerTask(), new CronTrigger(cron));
return "startTask";
}
@RequestMapping(value = "/stopTask.do", method = RequestMethod.POST)
public String stopTask() {
stopTimeTask();
return "stopTask";
}
public void stopTimeTask() {
if (future != null) {
future.cancel(true);
}
}
}