springboot(五)定时任务、异步任务

42 阅读1分钟

定时任务

util/Mytask.java

package com.example.springboot2.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.time.LocalDateTime;

@Configuration
@EnableScheduling
@Slf4j
public class Mytask {
    @Scheduled(cron = "*/5 * * * * ?")
    public void publishMsg(){
        log.warn("开始执行任务:"+ LocalDateTime.now());
    }
}

image.png

异步任务

声明异步任务

@Component: 注解:组件

package com.example.springboot2.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;

@Component
@EnableAsync
@Slf4j
public class MyAsyncTask {
    public void publishMsg(){
        try{
            Thread.sleep(5000);
            log.warn("异步任务处理完毕");
        }
        catch (InterruptedException e){
            e.printStackTrace();
        }
    }
}

调用异步任务

@Autowired: 注解:引入组件

package com.example.springboot2.controller;

import com.example.springboot2.util.MyAsyncTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController()
@RequestMapping("test")
@Slf4j
public class TestController {
    @Autowired
    private MyAsyncTask myAsyncTask;

    @GetMapping("getAsyncTask")
    public String getMyConfig() {
        myAsyncTask.publishMsg();
        log.info("这是跳过异步任务的执行");
        return "这是跳过异步任务的执行";
    }
}