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

介绍

这种方式,最简单,只需要两个注解和一个类即可

缺点:单线程,如果开启多个定时任务,只有上一个任务执行后,才能执行下一个任务,所以下一个任务可能会错过执行时间

如:

  1. 第一个任务是 1:00 执行,需要执行10分钟
  2. 第二个任务是 1:05 执行

结果:由于第一个任务执行结束后是 1:10 分,然后再过 5 分钟,第二个任务才会执行

第一步-开启定时任务

在启动类的类名上,加上下面注解,表示启动定时任务

@EnableScheduling

例子

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

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

第二步-创建定时任务类

在类名上加上下面注解:

@Component

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

@Scheduled

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

例子

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_1IX5tQWQTEnr.html