springboot异步调度任务

调度单例

import cn.hutool.extra.spring.SpringUtil;
import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class AsyncManager {

    /**
     * 操作延迟10毫秒
     */
    private final int OPERATE_DELAY_TIME = 10;

    /**
     * 异步操作任务调度线程池
     */
    private ScheduledExecutorService executor = SpringUtil.getBean(ScheduledExecutorService.class);

    private AsyncManager(){}

    private static AsyncManager me = new AsyncManager();

    public static AsyncManager me() {return me;}

    public void execute(TimerTask task) {
        executor.schedule(task,OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS);
    }
}

任务类

import cn.hutool.extra.spring.SpringUtil;
import com.flydiy.sample.auto.dao.OperatorLogMapper;
import com.flydiy.sample.auto.pojo.po.OperatorLogPO;
import java.util.TimerTask;

public class AsyncFactory {

    /**
     * 操作日志保存异步方法
     * @return
     */
    public static TimerTask recordOper(OperatorLogPO operatorLog) {
        return new TimerTask() {
            @Override
            public void run() {
                OperatorLogMapper mapper = SpringUtil.getBean(OperatorLogMapper.class);
                mapper.insert(operatorLog);
            }
        };
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot提供了多种异步处理的方式,其中比较常用的有以下几种: 1. 使用@Async注解 在Spring Boot中,我们可以使用@Async注解将一个方法声明为异步方法。在调用该方法时,Spring会开启一个新的线程执行该方法,并立即返回一个CompletableFuture对象,表示异步结果。需要注意的是,@Async注解需要配合@EnableAsync注解一起使用,以启用Spring异步处理功能。 示例代码: ```java @Service @EnableAsync public class AsyncService { @Async public CompletableFuture<String> asyncMethod() { // 执行异步操作 return CompletableFuture.completedFuture("异步操作完成"); } } ``` 2. 使用CompletableFuture CompletableFuture是Java 8中新增的一个异步处理工具类,可以用于实现异步任务的执行、结果合并、异常处理等。在Spring Boot中,我们可以使用CompletableFuture来实现异步处理,具体使用方式如下: ```java @Service public class AsyncService { public CompletableFuture<String> asyncMethod() { return CompletableFuture.supplyAsync(() -> { // 执行异步操作 return "异步操作完成"; }); } } ``` 3. 使用@Scheduled注解 @Scheduled注解可以用于定时任务调度,也可以用于异步任务调度。在Spring Boot中,我们可以使用@Scheduled注解来实现异步任务调度,具体使用方式如下: ```java @Service public class AsyncService { @Scheduled(fixedDelay = 1000) public void asyncMethod() { // 执行异步操作 } } ``` 需要注意的是,@Scheduled注解需要配合@EnableScheduling注解一起使用,以启用Spring的定时任务功能。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值