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);
}
}
}