您的位置:首页 > 编程语言 > Java开发

SpringBoot 创建定时任务

2018-07-08 19:01 141 查看
版权声明: https://blog.csdn.net/qq_38164123/article/details/80961562 一、在 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】 定时任务未开启 =================");
}
}

}

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: