[ Schedule task for specific time from spring 4 web mvc ]
I am building a Spring 4 Rest API for a trade automation site.
An http request will contain some info along with a date-time. After inserting these info into database (using hibernate), I need to dynamically create a new cron job which will access these db info and do something. The cron job must be executed at the time specified above.
So there wont be a fixed cron expression, also the cron task must access my DAO layer annoted with @Repository. Even after referring a lot of post in stack and other blog, which tells about @Scheduled, Spring-Quartz integration, I couldn't find out a solution for my specific need.
Java/Annotation configuration is preferred.
Please help. Thanks
Answer 1
I think you may use something like this: https://ha-jdbc.github.io/apidocs/net/sf/hajdbc/util/concurrent/cron/CronThreadPoolExecutor.html
Answer 2
You can use Trigger and TaskScheduler interfaces. Example below. To cancel job in the future it will be needed to store ScheduledFuture
instance.
@Configuration
public class AppConfiguration {
@Bean
public ThreadPoolTaskScheduler taskScheduler() {
return new ThreadPoolTaskScheduler();
}
}
@Controller
public class TriggerService {
@Autowired
private TaskScheduler scheduler;
@Autowired
private DAOService db;
private ScheduledFuture job;
@GetMapping("/task1")
@ResponseBody
public void triggerMyTask(@RequestParam String cronExpression) {
Runnable runnable = new Runnable() {
@Override
public void run() {
log.info(new Date());
/**
* here You can do what You want with db
* using some DAOService
*/
db.count();
}
};
/**
* cancel current task if You need
*/
if(job != null) {
job.cancel(true);
}
CronTrigger trigger = new CronTrigger(cronExpression);
job = scheduler.schedule(runnable, trigger);
}
}
You can pass cron expression for example like that:
http://localhost:8080/task1?cronExpression=0/5%20*%20*%20*%20*%20*