Java定時器內調用數據庫查詢信息---踩到的坑


今天使用Java定時任務的時候遇到了一個坑,就是在使用定時器的時候,直接在定時器內操作了數據,結果報空指針異常,查了貼子才發現,原來是定時器內不允許操作數據,這里貼出了定時器內操作數據的實例,方便使用的小伙伴們早些棄坑

定時器內不允許直接調用services層的方法來進行數據操作,所以我們可以直接將實現類的方法寫到這個地方,實現直接調用方法的情況


package com.zxjs.config;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zxjs.dao.ComplaintsDao;
import com.zxjs.entity.Complaints;
import com.zxjs.service.ComplaintsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;

import javax.annotation.Resource;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @author nan
 * @date 2020/7/24 15:07
 */
@Configuration
public class ConfigClass implements InitializingBean {

    private final static Logger logger = LoggerFactory.getLogger(ConfigClass.class);
    @Autowired
    private static ComplaintsService complaintsService;
    @Resource
    private ComplaintsDao complaintsDao;
    /**
     * 項目開啟的時候執行定時任務,用來檢測投訴保存是否到達五天
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        /**
         * 延遲60秒啟動,每一小時執行一次
         */
        try{
            new Timer("testTimer").schedule(new TimerTask() {
                @Override
                public void run() {
                    QueryWrapper<Complaints> wrapper = new QueryWrapper<>();
                    //查詢的是信息類型是保存的類型
                    wrapper.eq("complaintsActionType",0);
                    List<Complaints> list = complaintsDao.selectList(wrapper);
                    for (Complaints complaints : list) {
                        //判斷時長是否到達五天,到達的話獲取這個數據的id改變這條數據為不顯示狀態
                        //先判斷毫秒值是不是空,是空的話直接進行下一步
                        if(complaints.getComplaintsActionsMils() != null && !complaints.getComplaintsActionsMils().equals(null)&& complaints.getComplaintsActionsMils() != null){
                            if((System.currentTimeMillis() / 1000) - Long.parseLong(complaints.getComplaintsActionsMils()) > 432000){
                                //0:顯示;1不顯示,設置為不顯示
                                //只有當顯示為0的時候才會進行更新,這樣可以減少數據庫執行時間
                                if(complaints.getComplaintsShow() != "1" && !complaints.getComplaintsShow().equals("1")){
                                    complaints.setComplaintsShow("1");
                                    complaintsDao.updateById(complaints);
                                }
                            }
                        }
                        }}
            }, 60000,3600000);
        }catch (Exception e){
            logger.error(e.getMessage());
        }
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM