SpringBoot笔记十五:任务

异步任务

注解:@Async,@EnableAsync

我新建一个Service,就叫AsyncService

package com.example.service;
import org.springframework.stereotype.Service;
@Service
public class AsyncService {

    public void hello(){
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("处理数据中...");
    }
}

我线程休眠了5秒,再看看我的Controller

package com.example.controller;

import com.example.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class AsyncController {

    @Autowired
    AsyncService asyncService;

    @GetMapping("/hello")
    public String hello (){
        asyncService.hello();
        return "hello 许嵩";
    }
}

运行一下,访问http://localhost:8080/hello,要等待5秒才会有结果啊,我不想等怎么办?使用异步任务。在Service方法上加一个@Async注解,在Mainapplication主方法上加上@EnableAsync开启异步注解

@EnableAsync
public class MainApplication {...
    
@Async
public void hello(){...   

然后重启项目,你会发现,可以瞬间访问了。

定时任务

注解:@Scheduled,@EnableScheduling

新建一个Service,叫ScheduleService,我直接在MainApplication加上@EnableScheduling注解了

package com.example.service;

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

@Service
public class ScheduledService {
    @Scheduled(cron = "* * * * * MON-SAT")
    public void hello(){
        System.out.println("许嵩");
    }
}

运行,发现控制台每一秒都会打印出许嵩,这里讲解一下,更多的自己去查

cron=秒 分 时 日 月 周几
*是所有,枚举用逗号,时区用-,间隔是/
@Scheduled(cron = "* * * * * MON-SAT")//周一到周六,每秒执行一次
@Scheduled(cron = "0 * * * * MON-SAT")//0秒执行
@Scheduled(cron = "0,1,2,3 * * * * MON-SAT")//0至3秒的时候执行
@Scheduled(cron = "0-3 * * * * MON-SAT")//0至3秒执行
@Scheduled(cron = "0/3 * * * * MON-SAT")//每隔3秒执行
原文地址:https://www.cnblogs.com/yunquan/p/10443090.html