
import java.text.SimpleDateFormat;
import java.util.Date; import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component; /**
* 测试spring定时任务执行
*/
@Component
@Configuration
@EnableScheduling
public class MyTestTask {
private static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); @Scheduled(cron="* * * * * *") // 关于定时任务执行时间,后续会在别的文章中添加
public void executeUpdateYqTask() {
System.out.println(Thread.currentThread().getName() + " >>> task one " + format.format(new Date()));
} @Scheduled(cron="* * * * * *")
public void executeRepaymentTask() throws InterruptedException {
System.out.println(Thread.currentThread().getName() + " >>> task two " + format.format(new Date()));
}
}
import java.util.concurrent.Executor; import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar; @Configuration
@EnableScheduling
public class ScheduleConfig implements SchedulingConfigurer, AsyncConfigurer{ /** 异步处理 */
public void configureTasks(ScheduledTaskRegistrar taskRegistrar){
TaskScheduler taskScheduler = taskScheduler();
taskRegistrar.setTaskScheduler(taskScheduler);
} /** 定时任务多线程处理 */
@Bean(destroyMethod = "shutdown")
public ThreadPoolTaskScheduler taskScheduler(){
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(20);
scheduler.setThreadNamePrefix("task-");
scheduler.setAwaitTerminationSeconds(60);
scheduler.setWaitForTasksToCompleteOnShutdown(true);
return scheduler;
} /** 异步处理 */
public Executor getAsyncExecutor(){
Executor executor = taskScheduler();
return executor;
} /** 异步处理 异常 */
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler(){
return new SimpleAsyncUncaughtExceptionHandler();
}
}
最后:
在启动类加上 @EnableScheduling 就可以了
/**
* 启动类
*/
@SpringBootApplication
@EnableScheduling
public class AppApplication extends SpringBootServletInitializer {}