鍍金池/ 問(wèn)答/Java/ Spring項(xiàng)目中,執(zhí)行用戶設(shè)定的定時(shí)任務(wù)(用戶給某人定時(shí)發(fā)送郵件)

Spring項(xiàng)目中,執(zhí)行用戶設(shè)定的定時(shí)任務(wù)(用戶給某人定時(shí)發(fā)送郵件)

Controller中如下:

    @RequestMapping("sendMailAtTime")
    public TMessage sendMailAtTime(Mail mail, long setTime) {
        Runnable runnable = () -> {
            System.out.println("定時(shí)任務(wù)開(kāi)始執(zhí)行");
            mailService.sendMail(mail);
            System.out.println("定時(shí)任務(wù)執(zhí)行完畢");
        };
        ScheduledUtil.addTask(runnable, setTime);
        return new TMessage(TMessage.CODE_SUCCESS, "設(shè)置定時(shí)任務(wù)成功:" + setTime);
    }

這是ScheduledUtil

public class ScheduledUtil {
    
    private static ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(SysConfig.MAX_POLL_SIZE);
    
    /**
     * 添加一個(gè)定時(shí)任務(wù)
     *
     * @param runnable 具體的任務(wù)體
     * @param execTime 指定執(zhí)行時(shí)間
     */
    public static void addTask(Runnable runnable, long execTime) {
        scheduledThreadPool.schedule(runnable, getDelaySecond(execTime) + 1, TimeUnit.SECONDS);
    }
    
    /**
     * 得到與當(dāng)前時(shí)間相差秒數(shù)
     */
    public static long getDelaySecond(long time) {
        long res = (time - System.currentTimeMillis()) / 1000;
        return res > 0 ? res : 0;
    }
    
    public static void main(String[] args) {
    }
}

無(wú)論怎么調(diào)試,其實(shí)都不會(huì)執(zhí)行定時(shí)器的真正任務(wù)(sendMail),只會(huì)打印第一句話"定時(shí)任務(wù)開(kāi)始執(zhí)行",下斷點(diǎn)也捕捉不到sendMail,不知道是為什么。

是我的思路有問(wèn)題嗎。

回答
編輯回答
空白格

加上try catch看看是否有異常跑出。

2017年11月23日 10:21