繁体   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