一.主类上开启定时任务 @EnableScheduling
@SpringBootApplication
@MapperScan(basePackages = {"com.yy.springbootdemo.dao"})
@EnableScheduling //开启定时任务
public class SpringBootDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootDemoApplication.class, args);
}
}
二.定时类
package com.yy.springbootdemo.schedule;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.Date;
@Configuration //表示这是一个配置类,可以被扫描到,写@Component也行
public class TimeCron {
/**
* 每秒执行一次。
*/
@Scheduled(cron = "1-59 * * * * ? ")
public void cron(){
System.out.println(new Date());
System.out.println(System.currentTimeMillis());
}
}
三.结果