spring-boot 定时任务

一、创建项目java

@SpringBootApplication
@EnableAsync
@EnableScheduling
@EnableAutoConfiguration(exclude={  DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class})  
@ImportResource("classpath:spring.xml")

@EnableAsync 开启异步支持spring

@EnableScheduling 开启定时任务支持数据库

@EnableAutoConfiguration做用 Spring Boot会自动根据你jar包的依赖来自动配置项目。例如当你项目下面有HSQLDB的依赖时,Spring Boot会建立默认的内存数据库的数据源DataSource,若是你本身建立了DataSource,Spring Boot就不会建立默认的DataSource。异步

@ImportResource("classpath:spring.xml")  导入一些常规性配置,虽然spring-boot不推荐用xml了,可是原本仍是有些习惯用xml来配置async

 

二、spring-boot

@Component
public class TaskTest {

	@Scheduled(cron="0/30 * * * * ?")
	public void task(){
		System.out.println("========每30秒运行一次=======");
	}
}

这样一个简单的定时任务做业系统就完成了spa

 

问题:下面说说过程当中遇到的一个小坑,至今我都没搞明白的一个问题主要是异常任务问题code

@Scheduled(cron="0/30 * * * * ?")
	public void task1(){
        asyn();
		System.out.println("========每30秒运行一次=======");
	}
	
	@Async
	public void asyn(){
		System.out.println("========异步任务=======");
	}

看到代码,很简单明了,30秒运行一次task1方法,而task1方法则调用了一个异步方法,可是问题就出在这里,若是这样写的会,他这里只会同步执行异步任务,这里百思不得其解。xml

个人解决办法内存

@Component
public class TaskTest {
	
	@Autowired
	private AsyncTask asyncTask;

	
	@Scheduled(cron="0/30 * * * * ?")
	public void task1(){
		asyncTask.asyn();//调用异步任务
		System.out.println("========每30秒运行一次=======");
	}
}

异步方法不在原来定时做业的class里,这样就能够异步做业了,不明白这里的缘由,若是有人知道麻烦告诉一下

@Component
public class AsyncTask {

	@Async
	public void asyn() throws InterruptedException{
		Thread.sleep(5000);
		System.out.println("========异步任务=======");
	}
}
相关文章
相关标签/搜索