SSM---SpringMVC+Spring+Mybatis项目整合定时任务(可手动开启、手动关闭、手动设置时间)

1.编写定时任务逻辑

@Component
@EnableScheduling
public class SchedulerTask implements Runnable{
	
	
	@Override
	public void run() {
		System.out.println("定时任务!!!");
	}

}

   可以在run方法中使用Service层查询数据库:在run方法中使用Service层

2.在Spring配置文件中配置ThreadPoolTaskScheduler实例


3.编写开启定时任务和关闭定时任务的接口

import java.io.UnsupportedEncodingException;
import java.util.concurrent.ScheduledFuture;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.ssm.component.SchedulerTask;

@RestController
public class TaskController {
	

	@Autowired
	private ThreadPoolTaskScheduler threadPoolTaskScheduler;

	private ScheduledFuture future;

	
	
	

	/**
	 * DESC : 开启定时任务,时间为非必传参数,如果不传时间,就用默认的时间    
	 * @throws UnsupportedEncodingException 
	 * 
	 */
	@RequestMapping(value = "/startTask.do", method = RequestMethod.GET)
	public String startTask(String time) throws UnsupportedEncodingException {		// */5 * * * * ?
		stopTask(); 					//如果之前已经存在定时任务,就关闭		
		String cron = "";	
		if(time == null || time == "") {
			cron = "*/5 * * * * ?";
		}else {
			cron = time;
		}
		future = threadPoolTaskScheduler.schedule(new SchedulerTask(), new CronTrigger(cron));	//开启定时任务
		return "startTask";
	}

	

	/**
	 *  DESC : 关闭定时任务
	 * 
	 */
	@RequestMapping(value = "/stopTask.do", method = RequestMethod.GET)
	public String stopTask() {
		if (future != null) {
			future.cancel(true);
		}
		return "stopTask";
	}

}

 

你可能感兴趣的:(SSM---SpringMVC+Spring+Mybatis项目整合定时任务(可手动开启、手动关闭、手动设置时间))