簡體   English   中英

僅在顯式調用方法時如何啟動@scheduled cron?

[英]How to start @scheduled cron only when method is explicitly called?

默認情況下,@ Scheduled會在運行時自動啟動,即使不顯式調用該方法也是如此。

我希望僅在我顯式調用該方法時才能啟動cron計時器,因此可以在我的代碼中看到:

    @GetMapping("/checkstatus")
    public void getExistingTransaction(@RequestBody String uniq_id){
    //get Existing Transaction using uniq_id:
        //cases: uniq_id found, uniq_id not found:
    //if uniq_id is found: Find Transaction by uniq_id
    if(transactionRepository.findByUniqueId(uniq_id) != null){
        //if uniq id exists and found: perform checking cron:
        testCron(); //<-- this is the cron method.
    }
}

這是Cron方法的實現:

    //helper:
@Scheduled(cron = "*/10 * * * * *")
private void testCron() {
    long currentTime = System.currentTimeMillis() / 1000;
    logger.info("Transaction exists and cron stuff workz" + currentTime);
}

我的問題是: 無論何時滿足業務邏輯,如何控制它的執行以及如何停止它?

您可以使用started標志:

private boolean started = false;

private void startCron() {
    started = true;
}

private void stopCron() {
    started = false;
}

@Scheduled(cron = "*/10 * * * * *")
private void testCron() {
    if (!started) {
        return;
    }
    //...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM