16.springboot任务调度

来源:互联网 发布:人力资源 知乎 编辑:程序博客网 时间:2024/06/10 11:34

1.开启任务调度

(1)app类@EnableScheduling注解
package com.tyf.scheduling;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.scheduling.annotation.EnableScheduling;@SpringBootApplication@EnableSchedulingpublic class App {    public static void main( String[] args ) throws Exception{     SpringApplication.run(App.class, args);    }    }


(2)bean方法@Scheduled注解定期执行

package com.tyf.scheduling;import java.text.SimpleDateFormat;import java.util.Date;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component;/* *  * @Scheduled(fixedRate = 5000) :上一次开始执行时间点之后5秒再执行 * @Scheduled(fixedDelay = 5000) :上一次执行完毕时间点之后5秒再执行 * @Scheduled(initialDelay=1000, fixedRate=5000) :第一次延迟1秒后执行,之后按fixedRate的规则每5秒执行一次 * @Scheduled(cron=” /5 “) :通过cron表达式定义规则,什么是cro表达式,自行搜索引擎。 *  *  */@Componentpublic class ScheduledTasks {    private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");    @Scheduled(fixedRate = 5000)    public void reportCurrentTime() {        log.info("The time is now {}", dateFormat.format(new Date()));    }}




原创粉丝点击