SpringBoot手动控制启动定时任务
在SpringBoot中启动定时任务只需要添加注解 @EnableScheduling
即可搞定,
package cn.org.kcis;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class StartApplication {
public static void main(String[] args) {
SpringApplication.run(StartApplication.class, args);
}
}
然后再Job类上面添加 @Component
和 @Scheduled
在任务的类上写@Component
在任务方法上写@Scheduled
package cn.org.kcis.xian.task;
import cn.org.kcis.xian.controller.IndexController;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.scheduling.annotation.Scheduled;
/**
* @Author : BaiKeyang
* @Date : Created in 2020/7/16 11:27
* @Description:
* @Modified By:
* @Version: $
*/
@Component
public class ScheduledService {
private static final Logger log = LogManager.getLogger(IndexController.class);
// 表示每隔1小时执行
@Scheduled(cron = "0 0 */1 * * ?")
public void test1(){
log.error("=====>>>>>test1 {}",System.currentTimeMillis());
}
// 表示每隔3分钟执行
@Scheduled(cron = "0 */3 * * * ?")
public void test2(){
log.error("=====>>>>>test2 {}",System.currentTimeMillis());
}
// 表示每天15分、45分 执行
@Scheduled(cron = "0 15/30 * * * ?")
public void test3(){
log.error("=====>>>>>test3 {}",System.currentTimeMillis());
}
// 每天的上午8点到20点执行
@Scheduled(cron = "0 0 8-20 * * ?")
public void test6(){
log.error("=====>>>>>test6 {}",System.currentTimeMillis());
}
// 表示每天8点30分执行
@Scheduled(cron = "0 0,30 0,8 ? * ? ")
public void test7() {
log.error("=====>>>>>test7 {}",System.currentTimeMillis());
}
// 表示每天凌晨1点执行
@Scheduled(cron = "0 0 1 * * ?")
public void test8() {
log.error("=====>>>>>test8 {}",System.currentTimeMillis());
}
// 表示每隔3秒
@Scheduled(fixedRate = 3000)
public void test4() {
log.info("=====>>>>>test4{}", System.currentTimeMillis());
}
// 表示方法执行完成后5秒
@Scheduled(fixedDelay = 5000)
public void test5() {
log.info("=====>>>>>test5{}",System.currentTimeMillis());
}
}
启动项目后,注解的方法都会根据配置的cron表达式、fixedDelay和fixedRate 参数值去开始运行。
如果需要手动的去启动定时任务,再在上面定义实现了ThreadPoolTaskScheduler的实例:
package cn.org.kcis;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
@SpringBootApplication
@EnableScheduling
public class StartApplication {
public static void main(String[] args) {
SpringApplication.run(StartApplication.class, args);
}
@Bean
public ThreadPoolTaskScheduler threadPoolTaskScheduler () {
return new ThreadPoolTaskScheduler();
}
}
创建任务类,注入 ThreadPoolTaskScheduler
,通过 threadPoolTaskScheduler.schedule()
来创建、启动定时任务,并将任务保存,以便于下次关闭;
package cn.org.kcis.xian.task;
import cn.hutool.core.util.StrUtil;
import cn.org.kcis.xian.controller.IndexController;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;
/**
* @Author : BaiKeyang
* @Date : Created in 2020/7/16 11:27
* @Description:
* @Modified By:
* @Version: $
*/
@Component
public class ScheduledService {
private static final Logger log = LogManager.getLogger(IndexController.class);
@Autowired
ThreadPoolTaskScheduler threadPoolTaskScheduler;
Map<String, ScheduledFuture<?>> futureMap;
public void start (String key) {
if(StrUtil.isNotEmpty(key)) {
if(futureMap == null){
futureMap = new HashMap<>();
}
if("test".equals(key)) {
ScheduledFuture<?> future1 = threadPoolTaskScheduler.schedule(new myTask1(), new CronTrigger("0/1 * * * * ?"));
futureMap.put("task1", future1);
} else if("server".equals(key)) {
ScheduledFuture<?> future2 = threadPoolTaskScheduler.schedule(new myTask2(), new CronTrigger("0 */3 * * * ?"));
futureMap.put("task2", future2);
} else if("ps".equals(key)) {
ScheduledFuture<?> future2 = threadPoolTaskScheduler.schedule(new myTask3(), new CronTrigger("0 */1 * * * ?"));
futureMap.put("task3", future2);
}
}
}
// 关闭指定的定时任务
public String stop (String key) {
if(futureMap != null && StrUtil.isNotEmpty(key) && futureMap.get(key) != null) {
futureMap.get(key).cancel(true);
}
System.out.println("定时任务已关闭");
return "定时任务已关闭";
}
private class myTask1 implements Runnable {
@Override
public void run() {
System.out.println("test" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
}
}
private class myTask2 implements Runnable {
@Override
public void run() {
log.error("=====>>>>>服务可用性扫描 {}",System.currentTimeMillis());
}
}
private class myTask3 implements Runnable {
@Override
public void run() {
log.error("=====>>>>>数据同步 {}",System.currentTimeMillis());
}
}
}
在外部通过Controller调用来实现手动开启/关闭某个任务的操作:
package cn.org.kcis.xian.controller;
import cn.org.kcis.xian.task.ScheduledService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @Author : BaiKeyang
* @Date : Created in 2020/2/4 17:37
* @Description:
* @Modified By:
* @Version: $
*/
@RestController(value = "demoController")
public class HelloController {
@Autowired
ScheduledService scheduledService;
@RequestMapping(value = "/run")
public String run(String key) {
scheduledService.start(key);
return "定时任务已启动";
}
@RequestMapping(value = "/stop")
public String stop(String key) {
scheduledService.stop(key);
return "定时任务已关闭";
}
}
通过上面的方式,这样就实现了SpringBoot中手动控制定时任务的效果了。