【SpringBoot】- 使用注解方式开启定时任务

定时任务是我们项目中经常会用到的一个点,项目中使用的是xxljob,但今天这里想要总结的是关于SpringBoot使用注解方式开启定时任务;

基于注解的单线程定时任务:

1、使用注解@Scheduled、@EnableScheduling

  • 启动类里面@EnableScheduling开启定时任务,自动扫描
@EnableScheduling  //开启同步任务
public class BrainstormApplication {

	public static void main(String[] args) {
		SpringApplication.run(BrainstormApplication.class, args);
	}
}

在这里插入图片描述

  • 定时任务业务类加注解@Component被容器扫描
  • 定时执行的方法加上注解@Scheduled(fixedRate=2000)定期执行一次
@Component
public class TestTask {
    @Scheduled(fixedRate = 2000)
    public void sum(){
        System.out.println("当前时间:"+new Date());
    }
}

在这里插入图片描述
定时任务执行结果:
在这里插入图片描述
2、常用注解配置:

cron 定时任务表达式@Scheduled(cron="*/1*****”)表示每秒1),crontab工具:https://tool.lu/crontab/

  • fixedRate:定时多久执行一次(上一次开始执行时间点后xx秒再次执行;)
  • fixedDelay:上一次执行能束时间点后xx秒再次执行
  • fixedDelayString:学符串形式,可以通过配置文件指定

异步任务定时:

通过注解:@EnableAsync、@Async

@Async为异步注解,放到方法上则只作用于该方法,放在类上则作用于该类中所有的方法,表示调用该方法的线程与此方法异步执行,需要配合@EnableAsync注解使用

  • 项目启动类添加注解:@EnableAsync
@EnableAsync //开启异步任务
public class BrainstormApplication {

	public static void main(String[] args) {
		SpringApplication.run(BrainstormApplication.class, args);
	}
}
  • 异步任务业务类:
@Component //添加注解@Component被容器扫描
@Async     //异步任务注解
public class AsyncTask {
    public void task1() throws InterruptedException{
        long begin=System.currentTimeMillis();
        Thread.sleep(1000L);
        long end=System.currentTimeMillis();
        System.out.println("任务1耗时="+(end-begin));
    }

    public void task2() throws InterruptedException{
        long begin =System.currentTimeMillis();
        Thread.sleep(2000L);
        long end=System.currentTimeMillis();
        System.out.println("任务2耗时="+(end-begin));
    }

    public void task3() throws InterruptedException{
        long begin=System.currentTimeMillis();
        Thread.sleep(3000L);
        long end=System.currentTimeMillis();
        System.out.println("任务3耗时="+(end-begin));
    }
}
  • Controller测试数据:
@RestController
@RequestMapping("/test")
public class TestController {
    @Autowired
    private AsyncTask task;

    @GetMapping("/test")
    private Object test() {
        long begin = System.currentTimeMillis();
        try {
            task.task1();
            task.task2();
            task.task3();
        } catch (Exception e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        System.out.println("执行总耗时 : " + (end - begin));
        return "test";
    }
 }
  • 执行结果:
    在这里插入图片描述
  • 使用注解@Async的方法会被当成子线程执行,也就是在主线程执行完成后再进行执行;
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值