springboot 定时任务@Scheduled实现解析

网友投稿 245 2022-12-26


springboot 定时任务@Scheduled实现解析

这篇文章主要介绍了springboot 定时任务@Scheduled实现解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

1、pom.xml中导入必要的依赖:

org.springframework.boot

spring-boot-starter-parent

2.0.1.RELEASE

org.springframework.boot

spring-boot-starter-web

org.springframework.boot

&http://lt;artifactId>spring-boot-starter-tomcat

2、写一个springboot的启动类:

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;

import org.springframework.context.http://annotation.ComponentScan;

import org.springframework.scheduling.annotation.EnableScheduling;

@ComponentScan(basePackages = { "com.xwj.tasks" })

@EnableScheduling // 开启定时任务

@EnableAutoConfiguration

public class App {

public static void main(String[] args) {

SpringAqazZvbvRpplication.run(App.class, args);

}

}

注意这里一定要加上@EnableScheduling注解,用于开启定时任务

3、开始写定时任务:

import org.springframework.scheduling.annotation.Scheduled;

import org.springframework.stereotype.Component;

@Component

public class ScheduleTask {

@Scheduled(fixedRate = 1000)

// @Scheduled(cron = "0 23-25 18 * * ?")

public void testSchedule() {

System.out.println("定时任务:" + System.currentTimeMillis());

}

}

解释:

@Scheduled注解:

1、fixedRate 以固定速率执行。以上表示每隔1秒执行一次

2、fixedDelay 以上一个任务开始时间为基准,从上一任务开始执行后再次调用

3、cron表达式。可以实现定时调用。

在使用的过程中,楼主觉得,如果只有一个定时任务,fixedRate与fixedDelay的效果是一样一样的


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:应用系统接口设计(应用系统接口设计方案)
下一篇:IDEA 自定义方法注解模板的实现方法
相关文章

 发表评论

暂时没有评论,来抢沙发吧~