SendMessageTask.java 2.21 KB
package cn.fw.hestia.server.task;

import cn.fw.hestia.domain.db.MessageHistory;
import cn.fw.hestia.domain.enums.MessageStateEnum;
import cn.fw.hestia.service.buz.MessageCenterBizService;
import cn.fw.hestia.service.data.MessageHistoryService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

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

import static cn.fw.hestia.common.constant.MessageConstant.MAX_FREQUENCY;

/**
 * @author : kurisu
 * @className : FollowNoticeTask
 * @description : 服务号消息定时任务
 * @date: 2020-08-25 16:57
 */
@Component
@ConditionalOnProperty(prefix = "task", name = "switch", havingValue = "on")
public class SendMessageTask {
    private final MessageCenterBizService messageCenterBizService;
    private final MessageHistoryService messageHistoryService;

    @Autowired
    public SendMessageTask(final MessageCenterBizService messageCenterBizService,
                           final MessageHistoryService messageHistoryService) {
        this.messageCenterBizService = messageCenterBizService;
        this.messageHistoryService = messageHistoryService;
    }

    /**
     * 发送模板消息
     */
    @Scheduled(initialDelay = 1000 * 10, fixedRate = 1000 * 10)
    @Transactional(rollbackFor = Exception.class)
    public void sendNotice() {
        List<MessageHistory> list = messageHistoryService.list(Wrappers.<MessageHistory>lambdaQuery()
                .eq(MessageHistory::getState, MessageStateEnum.MADA)
                .eq(MessageHistory::getYn, Boolean.TRUE)
                .lt(MessageHistory::getFrequency, MAX_FREQUENCY)
                .lt(MessageHistory::getSendTime, new Date())
                .last("limit 1000")
        );
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        for (MessageHistory history : list) {
            messageCenterBizService.sendMessage(history);
        }
    }
}