定时任务
在springboot中实现定时任务很简单
1,启动类上增加一个@EnableScheduling
注解
@EnableScheduling
@SpringBootApplication
public class SpringbootAsyncApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootAsyncApplication.class, args);
}
}
2,创建一个定时任务类,使用@Scheduled
注解
/**
* @author: chenmingyu
* @date: 2019/3/1 17:33
* @description: 定时任务
*/
@Component
public class Schedule {
@Scheduled(cron = "0/1 * * * * ?")
public void test() {
System.out.println("...测试...");
}
}
启动后,输出如下
异步调用
异步调用,指的是一个可以无需等待被调用方法的返回值就让操作继续进行的方法
springboot中实现异步调用
1,启动类上增加一个@EnableAsync
注解
@EnableAsync
@SpringBootApplication
public class SpringbootAsyncApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootAsyncApplication.class, args);
}
}
2,使用@async
注解
/**
* @author: chenmingyu
* @date: 2019/3/1 17:49
* @description: 异步调用
*/
@Component
public class UserTest {
@Async
public void testOne() throws Exception{
System.out.println("testOne 开始执行");
Thread.sleep(2000L);
System.out.println("testOne 执行结束");
}
@Async
public void testTwo() throws Exception{
System.out.println("testTwo 开始执行");
Thread.sleep(1000L);
System.out.println("testTwo 执行结束");
}
}
测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootAsyncApplicationTests {
@Autowired
private UserTest userTest;
@Test
public void contextLoads() throws Exception{
userTest.testOne();
userTest.testTwo();
//防止主线程执行完
Thread.sleep(5000L);
}
}
输出