Scheduling jobs with Quartz
Quartz is a Java library that can schdule tasks (using Job derived class). Let me show how you would use the scheduler. First, import the library.
The task that the scheduler runs must be a Job class derivative.
How you schedule:
Here the keyword value is set and the task is getting the value by calling context.getJobDetail().getJobDataMap().get().
<dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.3.0</version> </dependency> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz-jobs</artifactId> <version>2.3.0</version> </dependency>
The task that the scheduler runs must be a Job class derivative.
import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; public class NewsJob implements Job { @Override public void execute(JobExecutionContext context) throws JobExecutionException { try { String keyword = (String) context.getJobDetail().getJobDataMap().get("keyword"); System.out.println(keyword); // task } catch (Exception e) { // emit an error } } }
How you schedule:
public void cronJob(String keyword) { try { JobDetail job = JobBuilder.newJob(NewsJob.class).usingJobData("keyword", keyword) .withIdentity("trigger", "group").build(); Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger", "group").startNow() .withSchedule( SimpleScheduleBuilder.simpleSchedule().withIntervalInMilliseconds(1000*60*60).repeatForever()) .build(); Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); scheduler.scheduleJob(job, trigger); scheduler.start(); } catch (Exception e) { // emit an error } }
Here the keyword value is set and the task is getting the value by calling context.getJobDetail().getJobDataMap().get().
Comments
Post a Comment