I am trying to use Quartz 2.2.1 with spring boot. Im trying to declare a scheduled task that is supposed to write some datas into a file. My Job is defined like below :
public class JobTask implements Job {
@Autowired
JobController controller;
@Override
public void execute(JobExecutionContext arg0) throws JobExecutionException {
try {
controller.doPrintData();
} catch (Exception e) {
e.printStackTrace();
}
}
}
And then :
public class StartJob {
public static void main(final String[] args) {
final SchedulerFactory factory = new StdSchedulerFactory();
Scheduler scheduler;
try {
scheduler = factory.getScheduler();
scheduler.start();
} catch (SchedulerException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
scheduler = factory.getScheduler();
final JobDetailImpl jobDetail = new JobDetailImpl();
jobDetail.setName("My job");
jobDetail.setJobClass(JobTask.class);
final SimpleTriggerImpl simpleTrigger = new SimpleTriggerImpl();
simpleTrigger.setStartTime(new Date(System.currentTimeMillis() + 5000));
//simpleTrigger.setStartTime(dateOf(12, 58, 00,06,05,2016));
simpleTrigger.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY);
simpleTrigger.setRepeatInterval(5000);
simpleTrigger.setName("Trigger execution every 5 secondes");
scheduler.start();
scheduler.scheduleJob(jobDetail, simpleTrigger);
System.in.read();
if (scheduler != null) {
scheduler.shutdown();
}
} catch (final SchedulerException e) {
e.printStackTrace();
} catch (final IOException e) {
e.printStackTrace();
}
}
}
PS : I have tested my controller method 'doPrintData' and it works. But when I put it inside the execute method im facing the javaNullPointerException.
Spring Boot manages it for you. Remove the quartz dependency and just create a Service
for having scheduled executions:
@Service
public class JobScheduler{
@Autowired
JobController controller;
//Executes each 5000 ms
@Scheduled(fixedRate=5000)
public void performJob() {
controller.doPrintData();
}
}
And enable the task scheduling for your application:
@SpringBootApplication
@EnableScheduling
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class);
}
}
See also: