一、在 springboot 项目启动类上增加注解 @EnableScheduling
package io.huihai;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.scheduling.annotation.EnableScheduling;
@EnableScheduling
@SpringBootApplication
public class HuihainApplications extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(HuihainApplications.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(HuihainApplications.class);
}
}
二、创建定时任务对象
package io.huihai.modules.book.issue.scheduled;
import io.huihai.modules.book.issue.dao.BookIssueDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
/**
* @author
* @email java_pioneer@163.com
* @Date
*/
@Configuration
@EnableScheduling
public class FreeNumberResetsScheduled {
private Logger log = LoggerFactory.getLogger(getClass());
/**
* 是否开启定时任务,true开启,false关闭
*/
@Value("${issue.open}")
private boolean open;
/**
* 免费次数
*/
@Value("${issue.freeNumber}")
private Integer freeNumber;
@Autowired
private BookIssueDao bookIssueDao;
/**
* 每月1号 0:00:00 执行
*/
@Scheduled(cron = "0 0 0 1 * ?")
public void FreeNumberResets() {
if (open) {
log.info("================= 启动定时任务 【FreeNumberResets】 =================");
try {
bookIssueDao.freeNumberResets(freeNumber);
} catch (Exception e) {
e.printStackTrace();
log.info("================= 【FreeNumberResets】 定时任务任务执行失败!!! =================");
}
log.info("================= 【FreeNumberResets】 定时任务执行完毕。重置所有普通会员免费次数为: {} =================", freeNumber + "次。");
} else {
log.info("================= 【FreeNumberResets】 定时任务未开启 =================");
}
}
}