Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java job scheduler based on Redis?

I am looking to replace Quartz as a job scheduler in our project. We already use Redis with cluster support as a distributed cache layer and we thought that maybe we could use Redis for job scheduling too. Has anyone implemented job scheduling in Java using Redis? I searched but could not find a library for this purpose. So I am starting to think that this is maybe not a popular solution?

like image 627
Milen Kovachev Avatar asked Mar 25 '16 14:03

Milen Kovachev


2 Answers

Take a look at Redisson. It allows to schedule and execute tasks (with cron-expression support) using simple ScheduledExecutorService api and based on Redis queue.

Here is an example. First define a task using java.lang.Runnable interface. Each task can access to Redis instance via injected RedissonClient object.

public class RunnableTask implements Runnable {

    @RInject
    private RedissonClient redissonClient;

    @Override
    public void run() throws Exception {
        RMap<String, Integer> map = redissonClient.getMap("myMap");
        Long result = 0;
        for (Integer value : map.values()) {
            result += value;
        }
        redissonClient.getTopic("myMapTopic").publish(result);
    }

}

Submit it to Redis based ExecutorService.

RScheduledExecutorService executorService = redisson.getExecutorService("myExecutor");
RScheduledFuture<?> future = executorService.schedule(new CallableTask(), 10, 20, TimeUnit.MINUTES);

future.get();
// or cancel it
future.cancel(true);

// cancel by taskId
executorService.cancelTask(future.getTaskId());

Examples with cron expressions:

executorService.schedule(new RunnableTask(), CronSchedule.of("10 0/5 * * * ?"));

executorService.schedule(new RunnableTask(), CronSchedule.dailyAtHourAndMinute(10, 5));

executorService.schedule(new RunnableTask(), CronSchedule.weeklyOnDayAndHourAndMinute(12, 4, Calendar.MONDAY, Calendar.FRIDAY));

All tasks are distributed across Redisson nodes. You can run these nodes as much as you need.

like image 80
Nikita Koksharov Avatar answered Oct 01 '22 16:10

Nikita Koksharov


How about Redis Labs' redis-quartz:

RedisJobStore A Quartz Scheduler JobStore that uses Redis for persistent storage.

We'd appreciate any feedback you have :)

like image 30
Itamar Haber Avatar answered Oct 01 '22 17:10

Itamar Haber