SpringBoot中Scheduled代码实现

新建Maven项目SpringQuartz。

1.1 添加依赖

由于spring-boot-starter-web并没有依赖spring-conext-support,所以需要单独添加此依赖。

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.10.RELEASE</version>
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
    </dependency>
</dependencies>

  

1.1 创建启动类

新建com.bjsxt.QuartzApplication启动类

 

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

 

1.1 新建定时任务

新建com.bjsxt.scheduled.DemoScheduled类。

注意类上有@Component注解,启动项目就需要加载类及类中的@Scheduled注解。

 

@Component
public class DemoScheduled {
    @Scheduled(cron="0/2 * * * * *")
    public void testScheduled(){
        System.out.println("test scheduled");
    }
}

  

posted @ 2021-01-27 16:18  巧克力曲奇  阅读(185)  评论(0编辑  收藏  举报