1、在启动类上加上@EnableScheduling 即在这个包下:org.springframework.scheduling.annotation.EnableScheduling
2、将设定为任务的类定义为@Component
3、将设定为任务的类的方法上加上@Scheduled
2/3的代码如下:
@Component
public class TestTask {// 这种方式的缺点是停不了,只能把程序挂了@Scheduled(cron = "0/5 * * * * ?")public void zhixing(){System.out.println(new Date());}
}
执行结果如下:
2023-07-01 20:38:29.816 INFO 62800 --- [ main] com.jjw.searApplication : Started searApplication in 24.831 seconds (JVM running for 28.48)
Sat Jul 01 20:38:30 CST 2023
Sat Jul 01 20:38:35 CST 2023