Spring任务调度Scheduling Tasks

来源:互联网 发布:学而知之什么意思 编辑:程序博客网 时间:2024/05/19 15:20


第一步、创建maven工程,引入依赖

<parent>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-parent</artifactId>    <version>1.4.1.RELEASE</version></parent><dependencies>    <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-web</artifactId>    </dependency></dependencies>
第二步、创建调度任务
@Scheduled注解的方法不能有返回值,并且不能有形参

package hello;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;@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()));    }}
第三步、SpringBoot方式启动容器、测试
在@Configuration注解的类上添加@EnableScheduling注解,为@Scheduled提供调度支持

package hello;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.scheduling.annotation.EnableScheduling;@SpringBootApplication@EnableSchedulingpublic class Application {public static void main(String[] args) throws Exception {        SpringApplication.run(Application.class);}
第四步、启动项目检验!!!

@Scheduled Annotation
fixdDelay:以指定时间间隔调度(以方法执行结束时间为准)

@Scheduled(fixedDelay=5000)public void doSomething() {    // something that should execute periodically}

fixedRate:以指定时间间隔调度任务(以方法执行开始时间为准)

@Scheduled(fixedRate=5000)public void doSomething() {    // something that should execute periodically}

initialDelay:指定延迟后开始调度任务

@Scheduled(initialDelay=1000, fixedRate=5000)public void doSomething() {    // something that should execute periodically}

cron表达式: 如下表示只在工作日每5秒执行一次

@Scheduled(cron="*/5 * * * * MON-FRI")public void doSomething() {    // something that should execute on weekdays only}

 
原创粉丝点击