SpringBoot整合定时任务和异步任务

SpringBoot整合定时任务和异步任务

SpringBoot定时任务schedule讲解

简介:讲解什么是定时任务和常见的定时任务区别

什么是定时任务,使用场景
  • 某个时间定时处理某个任务
  • 发邮件、短信等
  • 消息提醒
  • 订单通知
  • 统计订单报表系统
常见定时任务
  • java自带的Java.util.Timer类配置比较麻烦,时间延后问题
  • Quartz框架:配置简单,xml或者注解适合分布式或着大型调度作业
  • SpringBoot自带框架
SpringBoot使用注解方式开启定时任务
  • 启动类里面@EnableScheduling开启定时任务,自动扫描
  • 定时任务业务类加注解@Component被容器扫描
  • 定时执行的方法加上注解@Scheduled(fixedRate=2000)定期执行一次

SpringBoot多种定时任务配置示例

SpringBoot常用定时任务表达式配置和在线生成器

在线生成器和基本信息
  • cron定时任务表达式@Scheduled(cron="*/1 * * * * *")表示每秒
  • fixedRate:定时多久执行一次(上一次开始执行时间点后xx秒再次执行;)
  • fixedDelay:上一次执行结束时间点后xx秒再次执行
示例
package net.xdclass.demoproject.schedule;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Random;

/**
 * 定时统计订单,金额
 */

@Component
class VideoOrderTask {
    //每2秒执行一次
    @Scheduled(fixedDelay = 4000)
    //@Scheduled(fixedRate = 4000)
    //@Scheduled(cron = "*/1 * * * * *")
    public void sum(){

        //正常的是从数据库中查询

        System.out.println(LocalDateTime.now() + " 当前交易额="+ Math.random());

        try {
            Thread.sleep(2000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

package net.xdclass.demoproject;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@ServletComponentScan
@EnableScheduling//开启定时任务
public class DemoProjectApplication {

	public static void main(String[] args) {

		SpringApplication.run(DemoProjectApplication.class, args);
	}
}

在这里插入图片描述

SpringBoot异步任务EnableAsync实例

简介:讲解什么是异步任务,和使用SpringBoot开发异步任务实战

什么是异步任务和使用场景
  • 适用于处理log、发送邮件、短信…等
    • 下单接口->查库存1000
    • 余额校验1500
    • 风控用户1000
  • 启动类里面使用@EnableAsync注解开启功能,自动扫描
  • 定义异步任务类并使用@Component标记组件被容器扫描,异步方法加上@Async

SpringBoot异步任务Future实例

简介:使用SpringBoot开发异步任务Future获取结果

定义异步任务类需要获取结果
  • 注意点:
    • 要把异步任务封装到类里面,不能直接写到Controller
    • 增加Future返回结果AsyncResult(“task执行完成”)
    • 如果需要拿到结果需要判断全部的task.isDone()
实例
  • 开启异步任务
    在这里插入图片描述

  • 关闭异步任务
    在这里插入图片描述

package net.xdclass.demoproject;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@ServletComponentScan
@EnableScheduling
@EnableAsync//开启异步
public class DemoProjectApplication {

	public static void main(String[] args) {

		SpringApplication.run(DemoProjectApplication.class, args);
	}

}

package net.xdclass.demoproject.task;

import net.xdclass.demoproject.domain.User;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import java.util.concurrent.Future;

@Component
@Async
public class AsyncTask {


    public void task1(){

        try {
            Thread.sleep(4000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(" task 1 ");

    }

    public void task2(){
        try {
            Thread.sleep(4000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(" task 2 ");
    }

    public void task3(){
        try {
            Thread.sleep(4000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(" task 3 ");
    }



    public Future<String> task4(){
        try {
            Thread.sleep(4000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(" task 4 ");

        return new AsyncResult<String>("task4");
    }




    public Future<String> task5(){
        try {
            Thread.sleep(4000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(" task 5 ");
        return new AsyncResult<String>("task5");
    }







}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot中,可以使用@Scheduled注解来实现定时任务,可以结合@Async注解来实现多线程异步。 首先,需要在启动类上添加@EnableAsync注解,开启异步支持。然后在要执行异步任务的方法上添加@Async注解。 接下来,可以使用Java中的Executor框架来创建线程池,用于执行异步任务。可以在应用程序中创建一个线程池,并使用@Async注解将任务提交给线程池执行。 下面是一个示例代码: ```java @Configuration @EnableAsync public class AsyncConfig { @Bean(name = "taskExecutor") public Executor taskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(10); executor.setMaxPoolSize(20); executor.setQueueCapacity(30); executor.setThreadNamePrefix("MyAsyncThread-"); executor.initialize(); return executor; } } @Service public class MyService { @Async("taskExecutor") @Scheduled(cron = "0 0 12 * * ?") //每天中午12点执行 public void myAsyncTask() { //异步任务内容 } } ``` 在上面的示例中,我们创建了一个名为“taskExecutor”的线程池,并将其注入到MyService中的myAsyncTask方法中。该方法使用@Async注解来指示它应该在异步线程中执行。@Scheduled注解指定了任务执行的时间。 需要注意的是,@Async注解只有在调用该方法的类通过Spring容器进行管理时才会生效。如果通过new关键字手动创建对象,@Async注解将不起作用。 希望这可以帮助你完成Spring Boot定时任务整合多线程异步的实现。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值