有个定时任务 scheduler.scheduleAtFixedRate,每隔 5s 去执行检查 redis 某个 key,存在则继续逻辑,不存在则不往下走,但这个定时任务还是一直运行的。有什么方法在 run 的时候如果 redis 的 key 不存在把这个 Task 删除掉或取消掉
1
codingKingKong 2018 年 10 月 23 日
没有试验, 试试这个?
```java /** * Terminates this timer, discarding any currently scheduled tasks. * Does not interfere with a currently executing task (if it exists). * Once a timer has been terminated, its execution thread terminates * gracefully, and no more tasks may be scheduled on it. * * <p>Note that calling this method from within the run method of a * timer task that was invoked by this timer absolutely guarantees that * the ongoing task execution is the last task execution that will ever * be performed by this timer. * * <p>This method may be called repeatedly; the second and subsequent * calls have no effect. */ public void cancel() ``` |
2
gaius 2018 年 10 月 23 日
用一个线程做?
|
3
kanepan19 2018 年 10 月 23 日
当然可以 任务提交的时候会返回一个期望, 然后 future.cancel()
|
4
D3EP 2018 年 10 月 23 日
每次执行完 task 再去注册 task 就行了。
|
5
D3EP 2018 年 10 月 23 日
直接用 schedule。
|
7
honeycomb 2018 年 10 月 23 日 via Android
|
8
D3EP 2018 年 10 月 23 日
```java
public class Main { private static final ScheduledExecutorService EXECUTOR_SERVICE = Executors.newSingleThreadScheduledExecutor(); public static void main(String[] args) { EXECUTOR_SERVICE.schedule(Main::task, 1, TimeUnit.SECONDS); } public static void task(){ if (true) { System.out.println("Continue"); EXECUTOR_SERVICE.schedule(Main::task, 1, TimeUnit.SECONDS); }else { System.out.println("Exit"); } } } ``` |
9
imwxxxcxx 2018 年 10 月 23 日 抛出一个运行时异常。
|
10
lihongjie0209 2018 年 10 月 24 日
|