1、加上@Scheduled注解
import com.xpf.utils.DateUtil;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class OrderJob {
@Scheduled(cron = "0/3 * * * * ? ")
public void autoCloseOrder(){
System.out.println("执行定时任:1111111111111");
}
}
其中cron的值,可以在在线Cron表达式生成器此网页中设置自己想要间隔的时间,自动生成对应的cron表达式。比如我这边设置的是每隔3秒,执行一次。
2、在启动的类中加上@EnableScheduling注解
@SpringBootApplication(exclude = DruidDataSourceAutoConfigure.class)
//开启定时任务
@EnableScheduling
public class HnqyhxApplication extends SpringBootServletInitializer {
/**
* 需要把web项目打成war包部署到外部tomcat运行时需要改变启动方式
*/
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(HnqyhxApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(HnqyhxApplication.class, args);
}
}
3、控制台输出结果