springboot 自带定时任务-基于注解的方式(多线程)

介绍

这种方式的定时任务,是 多线程 的,一个任务一个线程,不会干扰

第一步-开启定时任务

在启动类的类名上,加上下面注解

//启动定时任务
@EnableScheduling
//启动多线程方式
@EnableAsync

例子

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

@SpringBootApplication
@EnableScheduling
@EnableAsync
public class Main {
    public static void main(String[] args) {
        SpringApplication.run(Main.class,args);
    }
}

第二步-创建定时任务类

在类名上加上下面注解:

@Component

在定时执行方法上(必须是无参数的),加上下面注解(该注解配置cron表达式):

//表示是定时执行的方法,该注解中配置定时的方式
@Scheduled
//多线程的方式,即:一个线程执行一个任务,互相不会干扰
@Async

注意:该定时执行方法,必须是无参数的

注意:任务类实现自定接口

如果任务类 实现自定义接口,启动会报错,如下:

 because it is a JDK dynamic proxy that implements:
com.riching.welerp.service.api.project.service.ProjectService
Action:

Consider injecting the bean as one of its interfaces or forcing the use of CGLib-based proxies by setting proxyTargetClass=true on @EnableAsync and/or @EnableCaching.

解决:

注解 @EnableAsync 需要改成下面:

@EnableAsync(proxyTargetClass = true)

例子

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

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 定时任务类
 **/
@Component
public class Task
{
    @Scheduled(cron="0/5 * *  * * ? ")   //每5秒执行一次
    @Async
    public void execute() throws InterruptedException {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //设置日期格式
        System.out.println("定时任务:" + df.format(new Date()));
        Thread.sleep(10000);
        System.out.println("结束--");
    }
}

参考:
https://blog.csdn.net/pan_junbiao/article/details/109399280


原文出处:/show_1IX5tRaBb3BS.html