三十二、Spring Boot创建定时任务

                                Spring Boot创建定时任务

启动类:

package com.yang;

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

@SpringBootApplication
@EnableScheduling//开启定时任务
public class DubboSpringBootApplication {

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

定时任务类:

package com.yang.task;

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

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

@Component
public class ScheduledTasks {

    private static final SimpleDateFormat dataFormat=new SimpleDateFormat("HH:mm:ss");
    //    @Scheduled(fixedRate = 5000) :上一次开始执行时间点之后5秒再执行
    //    @Scheduled(fixedDelay = 5000) :上一次执行完毕时间点之后5秒再执行
    //    @Scheduled(initialDelay=1000, fixedRate=5000) :第一次延迟1秒后执行,之后按fixedRate的规则每5秒执行一次
    //    @Scheduled(cron="*/5 * * * * *") 通过cron表达式定义规则

    @Scheduled(fixedRate=1000)
    public void showCurrentTime(){
        System.out.println("时间为:"+dataFormat.format(new Date()));
    }
}

猜你喜欢

转载自blog.csdn.net/newbie_907486852/article/details/81451130