• 9.4.4. 取消计划任务

    9.4.4. 取消计划任务

    分布式调度任务服务提供了两张取消任务的方式:通过调用ScheduledFuture.cancel()方法或调用RScheduledExecutorService.cancelScheduledTask方法。通过对Thread.currentThread().isInterrupted()方法的调用可以在已经处于运行状态的任务里实现任务中断:

    1. public class RunnableTask implements Callable<Long> {
    2. @RInject
    3. private RedissonClient redissonClient;
    4. @Override
    5. public Long call() throws Exception {
    6. RMap<String, Integer> map = redissonClient.getMap("myMap");
    7. Long result = 0;
    8. // map里包含了许多的元素
    9. for (Integer value : map.values()) {
    10. if (Thread.currentThread().isInterrupted()) {
    11. // 任务被取消了
    12. return null;
    13. }
    14. result += value;
    15. }
    16. return result;
    17. }
    18. }
    19. RScheduledExecutorService executorService = redisson.getExecutorService("myExecutor");
    20. RScheduledFuture<Long> future = executorService.scheduleAsync(new RunnableTask(), CronSchedule.dailyAtHourAndMinute(10, 5));
    21. // ...
    22. future.cancel(true);
    23. // 或
    24. String taskId = future.getTaskId();
    25. // ...
    26. executorService.cancelScheduledTask(taskId);