SpringBoot 创建定时任务

10 篇文章 1 订阅
1 篇文章 0 订阅

一、在 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】 定时任务未开启 =================");
        }
    }


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值