什么是定时任务和常见定时任务区别
什么是定时任务,使用场景
- 某个时间定时处理某个任务
- 发邮件、短信等
- 消息提醒
- 订单通知
- 统计报表系统 --每天的访问的量订单等
- ....
常见定时任务
- Java自带的java.util.Timer类配置比较麻烦,时间延后问题
- Quartz框架: 配置更简单,xml或者注解适合分布式或者大型调度作业
- SpringBoot框架自带
SpringBoot使用注解方式开启定时任务
- 启动类里面 @EnableScheduling开启定时任务,定时自动扫描
- 定时任务业务类 加注解 @Component被容器扫描
- 定时执行的方法加上注解 @Scheduled(fixedRate=2000) 定期执行一次
package work.flyrun.demoproject1.schedule;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
/**
* @Program: demo-project1
* @Description: 定时统计订单,金额
* @Author: chen
* @Dates: 2020-11-09-20-06
* @Version:
**/
@Component
public class VideoOrderTask {
// @Scheduled(fixedRate = 2000)//任务不管是否结束都执行
// @Scheduled(fixedDelay = 2000)//任务结束之后执行
@Scheduled(cron="*/1 * * * * *")//个性化定时
public void sum(){
// System.out.println(LocalDateTime.now() +"当前交易额="+Math.random());
}
}
package work.flyrun.demoproject1;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;
@ServletComponentScan
@SpringBootApplication
@EnableScheduling
public class DemoProject1Application {
public static void main(String[] args) {
SpringApplication.run(DemoProject1Application.class, args);
}
}
springboot2.x异步任务EnableAsync
什么是异步任务和使用场景:适用于处理log、发送邮件、短信……等(减少用户的等待时间 相当于线程)
- 下单接口->查库存 1000
- 余额校验 1500
- 风控用户1000
启动类里面使用@EnableAsync注解开启功能,自动扫描
定义异步任务类并使用@Component标记组件被容器扫描,异步方法加上@Async
使用SpringBoot2.x开发异步任务Future获取结果
定义异步任务类需要获取结果
-
注意点:
- 要把异步任务封装到类里面,不能直接写到Controller
- 增加Future 返回结果 AsyncResult("task执行完成");
- 如果需要拿到结果 需要判断全部的 task.isDone()
@Autowired
private AsyncTask asyncTask;
@GetMapping("async")
public JsonData testAsync(){
long begin = System.currentTimeMillis();
// asyncTask.task1();
// asyncTask.task2();
Future<String> task4 = asyncTask.task4();
Future<String> task5 = asyncTask.task5();
for (;;){
if (task4.isDone() && task5.isDone()){
try {
String task4Result=task4.get();//自行定义一个线程睡眠模拟效果
System.out.println(task4Result);
String task5Result=task5.get();
System.out.println(task5Result);
}catch (ExecutionException e){//试图获取已通过抛出异常而中止的任务的结果时
e.printStackTrace();
}catch (InterruptedException e){//当在sleep中的线程被调用interrupt方法时,就会放弃暂停的状态
e.printStackTrace();
}
finally {
break;
}
}
}
long end = System.currentTimeMillis();
return JsonData.buildSuccess(end-begin);
}
对Future进行详细讲解
在并发编程中,我们经常用到非阻塞的模型,在之前的多线程的三种实现中,不管是继承thread类还是实现runnable接口,都无法保证获取到之前的执行结果。通过实现Callback接口,并用Future可以来接收多线程的执行结果。
Future表示一个可能还没有完成的异步任务的结果,针对这个结果可以添加Callback以便在任务执行成功或失败后作出相应的操作。
Future接口定义了主要的5个接口方法,有RunnableFuture和SchedualFuture继承这个接口,以及CompleteFuture和ForkJoinTask继承这个接口。
RunnableFuture
这个接口同时继承Future接口和Runnable接口,在成功执行run()方法后,可以通过Future访问执行结果。这个接口都实现类是FutureTask,一个可取消的异步计算,这个类提供了Future的基本实现,后面我们的demo也是用这个类实现,它实现了启动和取消一个计算,查询这个计算是否已完成,恢复计算结果。计算的结果只能在计算已经完成的情况下恢复。如果计算没有完成,get方法会阻塞,一旦计算完成,这个计算将不能被重启和取消,除非调用runAndReset方法。
FutureTask能用来包装一个Callable或Runnable对象,因为它实现了Runnable接口,而且它能被传递到Executor进行执行。为了提供单例类,这个类在创建自定义的工作类时提供了protected构造函数。
SchedualFuture
这个接口表示一个延时的行为可以被取消。通常一个安排好的future是定时任务SchedualedExecutorService的结果
CompleteFuture
一个Future类是显示的完成,而且能被用作一个完成等级,通过它的完成触发支持的依赖函数和行为。当两个或多个线程要执行完成或取消操作时,只有一个能够成功。
ForkJoinTask
基于任务的抽象类,可以通过ForkJoinPool来执行。一个ForkJoinTask是类似于线程实体,但是相对于线程实体是轻量级的。大量的任务和子任务会被ForkJoinPool池中的真实线程挂起来,以某些使用限制为代价。
Future接口主要包括5个方法
public interface Future<V> { /** * Attempts to cancel execution of this task. This attempt will * fail if the task has already completed, has already been cancelled, * or could not be cancelled for some other reason. If successful, * and this task has not started when {@code cancel} is called, * this task should never run. If the task has already started, * then the {@code mayInterruptIfRunning} parameter determines * whether the thread executing this task should be interrupted in * an attempt to stop the task. */ boolean cancel(boolean mayInterruptIfRunning); /** * Returns {@code true} if this task was cancelled before it completed * normally. */ boolean isCancelled(); /** * Returns {@code true} if this task completed. */ boolean isDone(); /** * Waits if necessary for the computation to complete, and then * retrieves its result. */ V get() throws InterruptedException, ExecutionException; /** * Waits if necessary for at most the given time for the computation * to complete, and then retrieves its result, if available. */ V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException; }
get()方法可以当任务结束后返回一个结果,如果调用时,工作还没有结束,则会阻塞线程,直到任务执行完毕
get(long timeout,TimeUnit unit)做多等待timeout的时间就会返回结果
cancel(boolean mayInterruptIfRunning)方法可以用来停止一个任务,如果任务可以停止(通过mayInterruptIfRunning来进行判断),则可以返回true,如果任务已经完成或者已经停止,或者这个任务无法停止,则会返回false.
isDone()方法判断当前方法是否完成
isCancel()方法判断当前方法是否取消
下一章介绍在线视频中所用到的数据库结构