springboot定时任务的两种方式

1.Scheduled 定时任务器
2.整合Quartz定时任务框架

一:使用Scheduled 定时任务器:
1.pom导入依赖

<!--Scheduled 定时任务器 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>

2.编写定时任务类 和 定时触发的方法

package com.example.springboot.schduled;

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

import java.util.Date;

@Component
public class ScheduledDemo {


    /**
     * 定时任务方法
     * @Scheduled 设置定时任务
     * cron表达式 定时任务触发时间的一个字符串表达形式
     */
    @Scheduled(cron ="0/2 * * * * ?" )
    public void scheduledMethod()
    {
        System.out.println("定时任务被触发:"+new Date());
    }
}

3.在主类中添加注解


@SpringBootApplication
@EnableSwagger2
@EnableScheduling
public class SpringbootApplication {

    public static void main(String[] args) {

        SpringApplication.run(SpringbootApplication.class, args);
    }

}

4.cron表达式:
springboot定时任务的两种方式
springboot定时任务的两种方式

二:整合Quartz定时任务框架