首先,我们需要搭建一个基于SpringBoot的项目,然后我们要在Application中设置启用定时任务功能@EnableScheduling。
启动定时任务
package com.ltf;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class MakeaFortuneApplication {
public static void main(String[] args) {
SpringApplication.run(MakeaFortuneApplication.class, args);
}
}
其中 @EnableScheduling 注解的作用是发现注解@Scheduled的任务并后台执行。
定时任务具体实现类
接下来我们来创建一个定时任务
package com.ltf.scheduler;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.