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).
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));
}
}
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With