搜索关键词:spring task:https://www.cnblogs.com/baixianlong/p/10659045.html
1、简单的定时任务实现
使用方式:
使用@EnableScheduling注解开启对定时任务的支持。
使用@Scheduled 注解即可,基于corn、fixedRate、fixedDelay等一些定时策略来实现定时任务。
EnableScheduling
@Configuration
@Profile("production")
@EnableScheduling
@EnableTransactionManagement
@EnableAspectJAutoProxy
public class PerfTestServiceConfig implements ApplicationContextAware {。。。}
@Configuration
@Profile("production")
@EnableScheduling
@EnableTransactionManagement
public class AgentManagerServiceConfig implements ApplicationContextAware {。。}
/**
* Send the ngrinder usage data to GA. It executes only once each day at midnight
*
* @since 3.2
*/
@Service
public class PeriodicCollectDataToGAService {
/**
* Send the number of executed test.
*/
@Scheduled(cron = "0 1 1 * * ?")
@Transactional
public void reportUsage() {}
}
在定时任务的方法加上@Async即可,默认使用的线程池为SimpleAsyncTaskExecutor(该线程池默认来一个任务创建一个线程,就会不断创建大量线程,极有可能压爆服务器内存。当然它有自己的限流机制,这里就不多说了,有兴趣的自己翻翻源码~)
/**
* Asynchronous Runner.
*
* @since 3.3
*/
@Service
public class InternalAsyncTaskService {
@Async
public void runAsync(Runnable runnable) {
runnable.run();
}
}