SpringBoot 定时任务

  1. 在启动类上面添加@EnableScheduling

   2、 添加一下两个个文件

 

链接:https://pan.baidu.com/s/1xsP2keT2SzJQjdgcwwKvRA 密码:n0ss

  • ScheduleJobs.java
package com.fangxuele.ocs.service.coms.schedule;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springside.modules.utils.base.ExceptionUtil;

/**
 * Created by zhouy on 2017/5/3.
 */
@Component
public class ScheduleJobs {
    private static final Logger logger = LoggerFactory.getLogger(ScheduleJobs.class);

    @Autowired
    private ScheduleService scheduleService;


    /**
     * 每天凌晨00点钟执行一次
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void cronJobDetailB() {
        //重置流水号
        scheduleService.resetSystemSerial();
        logger.warn("各种流水号清零重置成功!");
    }

    /**
     * 每十分钟执行一次
     */
    @Scheduled(cron = "0 10 * * * ?")
    public void orderAutoVerify() {
        try {
            //订单自动核销
            scheduleService.orderAutoVerify();
            logger.warn("订单自动核销定时任务完毕!");
        } catch (Exception e) {
            logger.warn("订单自动核销定时任务失败!" + ExceptionUtil.stackTraceText(e));
        }
        scheduleService.sessionAutoOffSale();
        logger.warn("到了活动的截止报名时间,相关场次需要下架操作定时任务完毕!");
    }

    /**
     * 每天19:40执行一次
     */
    @Scheduled(cron = "0 40 19 * * ?")
    public void changeCardStatus() {
        try {
            scheduleService.refreshCustomerCardIndate();
            logger.warn("刷新用户卡到期状态定时任务完毕!");
        } catch (Exception e) {
            logger.warn("刷新用户卡到期状态定时任务失败!" + ExceptionUtil.stackTraceText(e));
        }
    }

}

ScheduleService.java

package com.fangxuele.ocs.service.coms.schedule;

import com.alibaba.dubbo.config.annotation.Reference;
import com.fangxuele.ocs.common.constant.RedisCacheConstant;
import com.fangxuele.ocs.common.dictionary.CustomerCardDictionary;
import com.fangxuele.ocs.common.dictionary.EventSessionDictionary;
import com.fangxuele.ocs.common.dictionary.OrderStatusChangeDictionary;
import com.fangxuele.ocs.common.dictionary.OrderStatusDictionary;
import com.fangxuele.ocs.common.dto.cache.CustomerCacheDTO;
import com.fangxuele.ocs.inter.cache.service.RedisCacheService;
import com.fangxuele.ocs.inter.cache.service.wechat.CustomerCacheService;
import com.fangxuele.ocs.inter.wechat.service.miniapp.TemplateAsyncMsgService;
import com.fangxuele.ocs.mapper.domain.TCustomerCard;
import com.fangxuele.ocs.mapper.domain.TEventSession;
import com.fangxuele.ocs.mapper.domain.TOrder;
import com.fangxuele.ocs.mapper.domain.TOrderStatusChange;
import com.fangxuele.ocs.mapper.mapper.TCustomerCardMapper;
import com.fangxuele.ocs.mapper.mapper.TEventMapper;
import com.fangxuele.ocs.mapper.mapper.TEventSessionMapper;
import com.fangxuele.ocs.mapper.mapper.TOrderMapper;
import com.fangxuele.ocs.mapper.mapper.TOrderStatusChangeMapper;
import com.fangxuele.ocs.mapper.mapper.TSysUserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.utils.base.ExceptionUtil;
import org.springside.modules.utils.time.DateFormatUtil;

import java.util.Date;
import java.util.List;

/**
 * 定时任务执行Service
 * Created by zgob 2018-4-28
 */
@Service
@Transactional
public class ScheduleService {

    private static final Logger logger = LoggerFactory.getLogger(ScheduleService.class);

    @Autowired
    private TOrderMapper orderMapper;

    @Autowired
    private TSysUserMapper sysUserMapper;

    @Autowired
    private TOrderStatusChangeMapper orderStatusChangeMapper;

    @Autowired
    private TEventSessionMapper eventSessionMapper;

    @Autowired
    private TCustomerCardMapper customerCardMapper;

    @Reference(version = "1.0.0")
    private RedisCacheService redisCacheService;

    @Reference(version = "1.0.0")
    private CustomerCacheService customerCacheService;

    @Reference(version = "1.0.0")
    private TemplateAsyncMsgService templateAsyncMsgService;

    /**
     * 每日零点重置需要清零的流水号
     */
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void resetSystemSerial() {
        redisCacheService.putValueByHash(RedisCacheConstant.SerialNumber, RedisCacheConstant.CardOrderNum, "0");
        redisCacheService.putValueByHash(RedisCacheConstant.SerialNumber, RedisCacheConstant.DistributeCodeNum, "0");
        redisCacheService.putValueByHash(RedisCacheConstant.SerialNumber, RedisCacheConstant.OrderNum, "0");
    }

    /**
     * 每十分钟执行订单自动核销
     */
    public void orderAutoVerify() {
        //订单状态为待使用 和 核销方式为姓名加电话 的订单列表
        List<TOrder> orderList = orderMapper.selectToAutoVerifyList();
        Date now = new Date();
        Long robotUserId = sysUserMapper.selectRobotUser().getId();
        for (TOrder tOrder : orderList) {

            // 添加订单更改记录
            TOrderStatusChange statusChange = new TOrderStatusChange();
            statusChange.setOrderId(tOrder.getId());
            statusChange.setBeforeStatus(tOrder.getStatus());
            statusChange.setAfterStatus(OrderStatusDictionary.STATUS_TO_COMMENT);
            statusChange.setOperatorId(robotUserId);
            statusChange.setOperatorType(OrderStatusChangeDictionary.OPERATOR_TYPE_SYSTEM);
            statusChange.setCreateTime(now);
            statusChange.setUpdateTime(now);
            orderStatusChangeMapper.insert(statusChange);

            tOrder.setStatus(OrderStatusDictionary.STATUS_TO_COMMENT);
            tOrder.setAutoVerificationTime(now);
            tOrder.setVerificationTime(now);
            tOrder.setUpdateTime(now);
            orderMapper.updateByPrimaryKey(tOrder);

            // 给用户发模板消息
            try {
                String formId = customerCacheService.getFormIdByCustomerId(tOrder.getCustomerId());
                if (formId != null) {
                    CustomerCacheDTO customerCacheDTO = customerCacheService.getCustomerCacheByCustomerId(String.valueOf(tOrder.getCustomerId()));
                    String openId = customerCacheDTO.getMiniappOpenid();
                    String url = "pages/order/order";

                    String orderStatus = "订单已完成";
                    String goodsName = tOrder.getEventTitle();
                    String content = "";
                    if (tOrder.getEventHierarchy() == 4) {
                        content += DateFormatUtil.formatDate("yyyy年MM月dd日", tOrder.getEventDate());
                    }
                    content += tOrder.getSessionTitle() + "-" + tOrder.getSpecTitle() + "*" + tOrder.getNumber();
                    String tips = "感谢您的参与,如有问题可拨打客服电话:13521239150";
                    templateAsyncMsgService.orderComplete(openId, formId, url, orderStatus, goodsName, content, tips);
                }
            } catch (Exception e) {
                logger.error(ExceptionUtil.stackTraceText(e));
            }
        }
    }

    /**
     * 到了活动的截止报名时间,相关场次需要下架操作,不在前台展示,目前没有隐藏,前台还能报名;
     */
    public void sessionAutoOffSale() {
        List<TEventSession> tEventSessionList = eventSessionMapper.selectForSessionAutoOffSale();
        Date now = new Date();
        for (TEventSession tEventSession : tEventSessionList) {
            tEventSession.setStatus(EventSessionDictionary.STATUS_EXPIRED);
            tEventSession.setUpdateTime(now);
            eventSessionMapper.updateByPrimaryKey(tEventSession);
        }
    }

    /**
     * 定时任务:刷新用户卡到期状态
     */
    public void refreshCustomerCardIndate() {
        List<TCustomerCard> customerCardList = customerCardMapper.selectAllExpired();
        Date now = new Date();
        for (TCustomerCard customerCard : customerCardList) {
            customerCard.setStatus(CustomerCardDictionary.EXPIRED);
            customerCard.setUpdateTime(now);
            customerCardMapper.updateByPrimaryKeySelective(customerCard);
        }
    }


}

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页