七.Spring Boot与执行任务

本文详细介绍了如何在SpringBoot项目中实现异步任务和定时任务,包括配置支持、注解使用及cron表达式的解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.异步任务

示例

controller

package com.miracle.springboot.controller;

import com.miracle.springboot.service.AsynService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class AsynController {

    @Autowired
    AsynService asynService;

    @GetMapping("/hello")
    public String hello(){
        // 模拟用户发送 /hello 请求,然后controller调用业务层一个很耗时的方法,如果同步执行,那么页面将会很久才能得到响应
        asynService.hello();
        return "success";
    }
}

service

package com.miracle.springboot.service;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class AsynService {
    // 异步注解,标明这个方法异步执行
    @Async
    public void hello(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("处理数据中");
    }
}

main方法

package com.miracle.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
// 开启异步注解的支持
@EnableAsync
@SpringBootApplication
public class Springboot04TaskApplication {

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

}

二.定时任务

1.开启定时任务的支持

在 main 方法类中

package com.miracle.springboot;

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

// 开启定时注解的支持
@EnableScheduling
@SpringBootApplication
public class Springboot04TaskApplication {

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

}

2.在要执行的业务方法上添加任务

package com.miracle.springboot.service;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
public class ScheduledService {

    /**
     *     在方法上加 @Scheduled 注解
     *     initial-delay:设置web服务器启动后,要等多少毫秒开始执行定时任务
     *     fixed-delay:设定每隔多少毫秒执行一次定时任务
     *     cron:指定cron表达式
     */

    @Scheduled(cron = "*/5 * * * * ?") // 每个5秒执行一次hello方法
    public void hello(){
        System.out.println("hello...");
    }
}

3.cron表达式写法

详见
https://blog.youkuaiyun.com/qq_39013701/article/details/90668813

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值