eclipse中搭建springboot学习(13)---定时任务

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Gr_lbxx/article/details/83614884

启动类

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@ServletComponentScan

//启用定时任务
@EnableScheduling
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}
 

定时任务类

package com.example.demo1101;

import java.text.SimpleDateFormat;
import java.util.Date;

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

/*
 * fixedRate 说明
 * 
 * @Scheduled(fixedRate = 6000) :上一次开始执行时间点之后6秒再执行
 * 
 * @Scheduled(fixedDelay = 6000) :上一次执行完毕时间点之后6秒再执行
 * 
 * @Scheduled(initialDelay=1000, fixedRate=6000)
 * :第一次延迟1秒后执行,之后按fixedRate的规则每6秒执行一次
 * 
 */

@Component
public class ScheduleTask {
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
    private int count = 0;
    // @Scheduled 参数可以接受两种定时的设置,一种是我们常用的cron="*/6 * * * * ?",一种是 fixedRate =
    // 6000,两种都表示每隔六秒打印一下内容

    // 间隔六秒打印一次count
    @Scheduled(cron = "*/6 * * * * ?")
    public void run() {
        System.out.println(count++);
    }

    // 间隔六秒打印一次时间
    @Scheduled(fixedRate = 6000)
    public void reportCurrentTime() {
        System.out.println("现在时间:" + dateFormat.format(new Date()));
    }

}

猜你喜欢

转载自blog.csdn.net/Gr_lbxx/article/details/83614884
今日推荐