@Scheduled结合@Async实现异步定时任务

依赖

   <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <scope>provided</scope>
        </dependency>

注解

1.cron
按顺序排列:位数6—7位(最后一位可以非必填项)
在这里插入图片描述

简单实例

@EnableScheduling //启动定时任务  
@Configuration
public class ScheduledTask {
    @Autowired
    BookMapper bookMapper;
    //每2秒插入数据
    @Scheduled(cron="* 0/10 * * * * ")
    public void task(){
        Book book=new Book();
        book.setBookName("java56");
        bookMapper.insert(book);
        System.out.println("插入book成功!");
    }
}

/** 注意:@EnableScheduling可以注解在application上面,二选其一 **/
@SpringBootApplication
//@EnableScheduling
@MapperScan("com.mybatisplus.demo.mybatis.mapper")
public class MybatisApplication {
    public static void main(String[] args) {
        SpringApplication.run(MybatisApplication.class, args);
    }
}

异步方法实现定时任务:

一: 使用异步方法的前提

import com.zhkj.jtb.platform.commons.utils.DateUtil;
import com.zhkj.jtb.platform.report.ytsf.service.AlarmStatisticsSnapshotService;
import com.zhkj.jtb.platform.report.ytsf.service.GPSLiveService;
import com.zhkj.jtb.platform.report.ytsf.service.TripService;
import com.zhkj.jtb.platform.report.ytsf.service.VehicleAlarmService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executor;

@Data
@Configuration
@EnableAsync
@Slf4j
@ConfigurationProperties(prefix = "zl.async")//配置在xml里面的参数,没有取到就是使用类里面的默认值
public class AsyncConfig implements AsyncConfigurer {
    @Autowired
    private VehicleAlarmService vehicleAlarmService;
    @Autowired
    private AlarmStatisticsSnapshotService snapshotService;
    @Autowired
    private TripService tripService;
    @Autowired
    private GPSLiveService gpsLiveService;
    private Integer coreSize = 10;
    private Integer maxSize = 20;
    private Integer queueCapacity = 500;

    @Override
    public Executor getAsyncExecutor() {
        //线程池
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(coreSize);
        taskExecutor.setMaxPoolSize(maxSize);
        taskExecutor.setQueueCapacity(queueCapacity);
        taskExecutor.initialize();
        return taskExecutor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new MyAsyncUncaughtExceptionHandler();
    } 
    
    class MyAsyncUncaughtExceptionHandler implements AsyncUncaughtExceptionHandler{
	    @Override
	    public void handleUncaughtException(Throwable ex, Method method, Object... params) {
	    	//发生异常时的处理方式
	    }
	}
   }

二: 使用异步线程


//@Transactional(rollbackFor = Exception.class)//事务回滚,发生SQLException异常时回滚数据。(要么全执行,要么都不执行)
@Scheduled(cron ="0 0/5 0 1-2 * ?")//每天凌晨1-2每5分钟执行一次
@Async
public void monthStatistics(){
	//定时任务处理的业务逻辑
 }

**注意:@Async被该注解标识的方法是异步方法,
		就是它会给你在后台开启一个线程来处理被标识的方法,
		所有耗时任务会经常使用它
		
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 @Scheduled 注解中添加 @Async 注解可以实现定时任务异步执行。@Async 注解可以用于标记一个方法为异步方法,表示该方法将在一个独立的线程中执行,而不会阻塞当前线程。 下面是一个示例: ```java import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class MyScheduledTask { @Async @Scheduled(fixedRate = 5000) // 每隔5秒执行一次 public void myAsyncTask() { // 异步执行的任务逻辑 System.out.println("异步任务开始执行..."); // ... System.out.println("异步任务执行完成!"); } } ``` 在上述示例中,我们在定时任务方法上同时添加了 @Async 和 @Scheduled 注解。@Scheduled 注解用于配置定时任务的执行频率,这里使用 fixedRate 表示每隔5秒执行一次。@Async 注解表示该方法将异步执行。 需要注意的是,为了使 @Async 注解生效,还需要在 Spring Boot 的主类上添加 @EnableAsync 注解。 ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableAsync; @SpringBootApplication @EnableAsync public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } } ``` 这样配置之后,定时任务将在独立的线程中异步执行,不会阻塞当前线程。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值