springBoot 入门(六)—— 整合Spring框架开启自带的任务调度器执行任务(注解方式)

1.重新配置spring boot 启动类 application.java

package Controller;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@SpringBootApplication
@MapperScan(basePackages = {"mapper"}) // 自动扫描
@ComponentScan(basePackages = {"schedule"})
@EnableScheduling
@EnableAutoConfiguration
@EnableTransactionManagement//启用事物管理,在service上使用@Transactional(注意是spring的 注解)
public class Application {
//    static String classPath = new Application().getClass().getClassLoader().getResource("")+"";

    public static void main(String[] args) {

        SpringApplication.run(Application.class, args);
//        System.out.println("classpath: "+classPath);

        System.out.println("spring boot 启动成功!");
    }
}

2.在需要使用的地方使用注解@Scheduled来配置任务的具体调度时间等

package schedule;

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

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

@Component
public class TestTask {
    @Scheduled(cron = "0 * * * * ?")
    public void minuteJob() {
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())  +"  do somthing....");
    }
}

启动spring boot,观察后台日志

spring boot 启动成功!
2018-04-20 17:59:00  do somthing....
2018-04-20 18:00:00  do somthing....
2018-04-20 18:01:00  do somthing....

猜你喜欢

转载自blog.csdn.net/uniquewonderq/article/details/80022359
今日推荐