Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a cron-like implementation of ScheduledExecutorService in Java?

Tags:

java

scheduler

The ScheduledExecutorService in Java is pretty handy for repeating tasks with either fixed intervals or fixed delay. I was wondering if there is an something like the existing ScheduledExecutorService that lets you specify a time of day to schedule the task at, rather than an interval i.e. "I want this task to fire at 10am each day".

I know you can achieve this with Quartz, but I'd rather not use that library if possible (it's a great library but I'd rather not have the dependency for a few reasons).

like image 576
GaryF Avatar asked Jan 22 '09 16:01

GaryF


3 Answers

ThreadPoolTaskScheduler, can be used whenever external thread management is not a requirement. Internally, it delegates to a ScheduledExecutorService instance. ThreadPoolTaskScheduler implements Spring’s TaskExecutor interface too, so that a single instance can be used for asynchronous execution as well as scheduled, and potentially recurring, executions.

Where as CronTrigger() takes in cronExpression http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/support/CronSequenceGenerator.html

For more information on this solution refer Spring docs: https://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html

import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import java.util.Date;

public class CronTriggerSpringTest{
public static void main(String args[]){
    String cronExpression = "0/5 * * * * *";
    ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
    scheduler.initialize();
    scheduler.schedule(new Runnable() {
        @Override
        public void run() {
            System.out.println("Hello Date:"+new Date());
        }
    }, new CronTrigger(cronExpression));
}
}
like image 178
vijay Avatar answered Oct 20 '22 07:10

vijay


A bit more searching has turned up CronExecutorService in HA-JDBC. Interestingly, it has a dependency on Quartz for its CronExpression class, but that's it. That's not too bad.

Update: I've fixed the broken links to point at new versions, but I don't know if that is the only dependency any more

like image 44
GaryF Avatar answered Oct 20 '22 06:10

GaryF


You can use the Timer class. Specifically, scheduleAtFixedRate(TimerTask task, Date firstTime, long period). Where you can set a task to start at 10am on a particular day and repeat every 24 hours.

like image 3
neesh Avatar answered Oct 20 '22 08:10

neesh