springboot
定时任务的使用
1、启动类上添加@EnableScheduling
,开启定时任务
2、Scheduled
参数说明
cron
:cron表达式,指定任务在特定时间执行;
fixedDelay
:表示上一次任务执行完成后多久再次执行,参数类型为long,单位ms;
fixedRate
:表示按一定的频率执行任务,参数类型为long,单位ms;
initialDelay
:表示延迟多久再第一次执行任务,参数类型为long,单位ms;
3、配置定时任务执行为多线程及使用如下
@Configuration
@EnableScheduling
public class TestSchedule implements SchedulingConfigurer {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd-HH:mm:ss");
@Scheduled(cron = "0/5 * * * * ?")
public void testSchedule1() throws InterruptedException {
String dateTime = LocalDateTime.now(ZoneOffset.of("+8")).format(formatter);//字符串转时间String dateTimeStr = "2018-07-28 14:11:15";
System.out.println(Thread.currentThread()+"等上一次执行完,再等5秒钟在执行>>"+ dateTime);
Thread.sleep(10000L);
}
@Scheduled(fixedDelay=4000)
private void testSchedule3() throws InterruptedException {
String dateTime = LocalDateTime.now(ZoneOffset.of("+8")).format(formatter);
System.out.println(Thread.currentThread()+"等上次执行完再等两秒再执行>>"+ dateTime);
Thread.sleep(2000L);
}
@Scheduled(fixedRate=2000)
public void testSchedule4() throws InterruptedException {
String dateTime = LocalDateTime.now(ZoneOffset.of("+8")).format(formatter);
System.out.println(Thread.currentThread()+"每次两秒执行一次>>"+ dateTime);
System.out.println(Thread.currentThread()+"执行时候如果上一次已经执行结束,则直接执行>>"+ dateTime);
System.out.println(Thread.currentThread()+"执行时候如果上一次没执行结束,等执行结束立即执行>>"+ dateTime);
Thread.sleep(4000L);
}
@Scheduled(initialDelay = 10000,fixedRate = 15000)
private void testSchedule5(){
String dateTime = LocalDateTime.now(ZoneOffset.of("+8")).format(formatter);
System.out.println("项目启动10秒后再执行,每15秒固定执行一次>>"+ dateTime);
}
//设置定时任务执行为多线程的
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
//设置线程核数
taskRegistrar.setScheduler(Executors.newScheduledThreadPool(10));
}
}
springboot中异步方法使用
1、在启动类上@EnableAsync
开启异步执行任务
@ServletComponentScan
@SpringBootApplication
@EnableAsync
public class ActivityApplication {
public static void main(String[] args) {
try {
SpringApplication.run(ActivityApplication.class, args);
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
}
2、在要异步执行的方法或类上加@Async
注解
public interface ActivityLogInter {
Future<String> test() throws InterruptedException;
}
@Service
@Slf4j
public class ActivityLogImpl implements ActivityLogInter {
@Override
@Async
public Future<String> test() throws InterruptedException {
System.out.println("异步方法执行中");
//测试异步的使用
Thread.sleep(2000l);
Future<String> resultFuture=new AsyncResult<>("222");
System.out.println("异步方法执行完");
return resultFuture;
}
}
3、将对象注入后异步执行方法,阻塞获得返回值
@RestController
@RequestMapping("/test1")
@Slf4j
public class Test1Controller {
@Autowired
private ActivityLogInter activityLogImpl;
@GetMapping(value = "/time")
@ResponseBody
public void test() throws InterruptedException {
//这个方法是异步执行的
Future<String> future = activityLogImpl.test();
System.out.println("执行业务逻辑");
//阻塞获得返回值
String s = future.get();
System.out.println(s);
}
}