转载https://blog.csdn.net/amelia__liu/article/details/81940315
创建定时任务
@Scheduled 注解用于标注这个方法是一个定时任务的方法,有多种配置可选。cron支持cron表达式,指定任务在特定时间执行;fixedRate以特定频率执行任务;fixedRateString以string的形式配置执行频率。
package com.autonavi.task.test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.autonavi.task.ScheduledTasks;
@Component
public class ScheduledTest {
private static final Logger logger = LoggerFactory.getLogger(ScheduledTasks.class);
@Scheduled(cron="0 0/2 * * * ?")
public void executeFileDownLoadTask() {
// 间隔2分钟,执行任务
Thread current = Thread.currentThread();
System.out.println("定时任务1:"+current.getId());
logger.info("ScheduledTest.executeFileDownLoadTask 定时任务1:"+current.getId()+ ",name:"+current.getName());
}
}
启动定时任务
@EnableScheduling 注解的作用是发现注解@Scheduled的任务并后台执行。
@SpringBootApplication
@EnableScheduling
public class App {
private static final Logger logger = LoggerFactory.getLogger(App.class);
public static void main(String[] args) {
SpringApplication.run(App.class, args);
logger.info("start");
}
}
Springboot本身默认的执行方式是串行执行,也就是说无论有多少task,都是一个线程串行执行,并行需手动配置
并行任务
继承SchedulingConfigurer类并重写其方法即可,如下
@Configuration
//所有的定时任务都放在一个线程池中,定时任务启动时使用不同都线程。
public class ScheduleConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
//设定一个长度15的定时任务线程池
taskRegistrar.setScheduler(Executors.newScheduledThreadPool(20));
}
}
异步并行任务
@Configuration
@EnableScheduling
@EnableAsync(
mode = AdviceMode.PROXY, proxyTargetClass = false,
order = Ordered.HIGHEST_PRECEDENCE
)
@ComponentScan(basePackages = "hello")
public class RootContextConfiguration implement sAsyncConfigurer, SchedulingConfigurer {
@Bean
public ThreadPoolTaskScheduler taskScheduler(){
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(20);
scheduler.setThreadNamePrefix("task-");
scheduler.setAwaitTerminationSeconds(60);
scheduler.setWaitForTasksToCompleteOnShutdown(true);
return scheduler;
}
@Override
public Executor getAsyncExecutor()
{
Executor executor = this.taskScheduler();
return executor;
}
@Override
public void configureTasks(ScheduledTaskRegistrar registrar)
{
TaskScheduler scheduler = this.taskScheduler();
registrar.setTaskScheduler(scheduler);
}
}