• 9.4.2. 设定任务计划

    9.4.2. 设定任务计划

    Redisson独立节点不要求任务的类在类路径里。他们会自动被Redisson独立节点的ClassLoader加载。因此每次执行一个新任务时,不需要重启Redisson独立节点。

    采用Callable任务的范例:

    1. public class CallableTask 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. for (Integer value : map.values()) {
    9. result += value;
    10. }
    11. return result;
    12. }
    13. }

    在创建ExecutorService时可以配置以下参数:

    1. ExecutorOptions options = ExecutorOptions.defaults()
    2. // 指定重新尝试执行任务的时间间隔。
    3. // ExecutorService的工作节点将等待10分钟后重新尝试执行任务
    4. //
    5. // 设定为0则不进行重试
    6. //
    7. // 默认值为5分钟
    8. options.taskRetryInterval(10, TimeUnit.MINUTES);
    1. RScheduledExecutorService executorService = redisson.getExecutorService("myExecutor");
    2. ScheduledFuture<Long> future = executorService.schedule(new CallableTask(), 10, TimeUnit.MINUTES);
    3. Long result = future.get();

    使用Lambda任务的范例:

    1. RExecutorService executorService = redisson.getExecutorService("myExecutor", options);
    2. ScheduledFuture<Long> future = executorService.schedule((Callable & Serializable)() -> {
    3. System.out.println("task has been executed!");
    4. }, 10, TimeUnit.MINUTES);
    5. Long result = future.get();

    采用Runnable任务的范例:

    1. public class RunnableTask implements Runnable {
    2. @RInject
    3. private RedissonClient redissonClient;
    4. private long param;
    5. public RunnableTask() {
    6. }
    7. public RunnableTask(long param) {
    8. this.param= param;
    9. }
    10. @Override
    11. public void run() {
    12. RAtomicLong atomic = redissonClient.getAtomicLong("myAtomic");
    13. atomic.addAndGet(param);
    14. }
    15. }
    16. RScheduledExecutorService executorService = redisson.getExecutorService("myExecutor");
    17. ScheduledFuture<?> future1 = executorService.schedule(new RunnableTask(123), 10, TimeUnit.HOURS);
    18. // ...
    19. ScheduledFuture<?> future2 = executorService.scheduleAtFixedRate(new RunnableTask(123), 10, 25, TimeUnit.HOURS);
    20. // ...
    21. ScheduledFuture<?> future3 = executorService.scheduleWithFixedDelay(new RunnableTask(123), 5, 10, TimeUnit.HOURS);