1、静态定时任务
@Configuration //1.主要用于标记配置类,兼备Component的效果。
//@Component
@EnableScheduling // 2.开启定时任务
public class StaticTimedTask {
//3.添加定时任务
//指定执行时间
//@Scheduled(cron = "0/5 * * * * ?")
//或指定执行时间间隔,例如:5秒
//@Scheduled(fixedRate=5000)
public void configureTasks() {
System.err.println("执行静态定时任务时间: " + LocalDateTime.now());
}
}
2、基于spring的动态定时任务
controller
@RestController
@Api(description = "定时任务")
@RequestMapping("/schedule")
public class ScheduleController {
// 可利用线程存储器对多个定时任务进行管理
public static ConcurrentHashMap<String, ScheduledFuture> map = new ConcurrentHashMap<String, ScheduledFuture>();
@Autowired
private ConfigurationContent youXinConfiguration;
@Autowired
private ThreadPoolTaskScheduler threadPoolTaskScheduler;
private ScheduledFuture<?> future;
//创建线程
@Bean
public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
ThreadPoolTaskScheduler executor = new ThreadPoolTaskScheduler();
executor.setPoolSize(20);
executor.setThreadNamePrefix("taskExecutor-");
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setAwaitTerminationSeconds(60);
return executor;
}
@PostMapping("/startTask")
@ApiOperation("手动执行开始定时任务")
public String startTask() {
future = threadPoolTaskScheduler.schedule(new RunnableContent(),new Trigger(){
@Override
public Date nextExecutionTime(TriggerContext triggerContext){
return new CronTrigger(youXinConfiguration.getTaskTime()).nextExecutionTime(triggerContext);//测试时间
// return new CronTrigger(youXinConfiguration.getDay()).nextExecutionTime(triggerContext);
}
});
System.out.println("START!!!!!!!!!!");
return "success start";
}
@PostMapping("/stopTask")
@ApiOperation("手动执行关闭定时任务")
public String stopTask() {
if (future != null) {
future.cancel(true);
}
return "success stop";
}
}
ApplicationContextUtil
@Component
public class ApplicationContextUtil implements ApplicationContextAware {
/**
* 上下文对象实例
*/
private static ApplicationContext applicationContext;
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 获取applicationContext
*/
public void setApplicationContext(ApplicationContext applicationContext) {
ApplicationContextUtil.applicationContext = applicationContext;
}
/**
* 通过name获取 Bean.
*/
public static Object getBean(String beanName) {
return applicationContext.getBean(beanName);
}
/**
* 通过class获取Bean.
*/
public static <T>T getBean(Class<T> clazz) {
return applicationContext.getBean(clazz);
}
}
ConfigurationContent
@Data
@Component
@ConfigurationProperties(prefix = "executionTime")//获取yml配置
@EqualsAndHashCode(callSuper = false)
public class ConfigurationContent {
private String taskTime;//10s执行一次
// private String day;//一天执行一次
}
此处的时间需要同时再配置文件中配置,否则启动直接报错
executionTime:
taskTime: 0/15 * * * * ? #10s
day: 0 0 4 * * ? #每天4点触发方法
RunnableContent
public class RunnableContent implements Runnable {
@Override
public void run() {
//通过名字获取实例,同时需要在实例处加注释 *@Service("projectService")*
//ProjectServiceImpl projectService = (ProjectServiceImpl)ApplicationContextUtil.getBean("projectService");
//通过类名获取实例
ProjectService projectService = (ProjectService)ApplicationContextUtil.getBean(ProjectService.class);
Map<String,Object> map = projectService.test();
System.out.println(map);
}
}
StartService
//继承Application接口后项目启动时会按照执行顺序执行run方法通过设置Order的value来指定执行的顺序
@Component
@Order(value = 1)
public class StartService implements ApplicationRunner{
@Autowired
private ScheduleController scheduleController;
@Override
public void run(ApplicationArguments args) throws Exception {
//启动定时任务
scheduleController.startTask();
}
}