Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert data after completing job in Quartz scheduler using spring

I'm working on a task in which I need to save job status in database but when I tried to do this it gives me java.lang.nullpointerexception. I think it happen because whenever I tried to select/save/update any record from the database only at that time it gives me error similar to this.

Here is my code

public class PostFBJob implements Job {

    private SchedulerService schedulerService;

    private SubCampaignService subCampaignService;

    @SuppressWarnings("unchecked")
    public void execute(JobExecutionContext context) throws JobExecutionException {

        JobDetail jobDetail = context.getJobDetail();
        JobDataMap jobDataMap = jobDetail.getJobDataMap();

        schedulerService = (SchedulerService) jobDataMap.get("schedulerService");

        SubCampaign subCampaign = (SubCampaign) jobDataMap.get("subCampaign");

        if (prStreamItem.getName().equalsIgnoreCase("Facebook") && StringUtils.isNotBlank(branch.getFbAccessToken())) {
            FacebookService facebookService = FacebookService.getSingleton();
            try {
                subCampaign.setStatus("Completed");
                subCampaign.setMessage("Completed");

                subCampaignService.updateSubCampaign(subCampaign);

            } catch (Exception e) {
                log.error("", e);
            }
        }
    }
}

Exception

java.lang.NullPointerException
    at com.ace.Job.SubCampaignJob.execute(SubCampaignJob.java:147)
    at org.quartz.core.JobRunShell.run(JobRunShell.java:213)
    at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:557)
Error: java.lang.NullPointerException

Please help me to solve this issue. I'm new to Spring and Quartz.

Thanks in advance

like image 391
Ace Avatar asked Mar 15 '23 02:03

Ace


2 Answers

This exception due to null object of subCampaignService. Injection work only those objects which are managed by spring.

To scan your all packages where you want to use Service.

  1. Annotation based configuration

    @ComponentScan({"com.ace"})

  2. XML based configuration

    <context:component-scan base-package="com.ace"/>

And also check null before update like below:

try {
    subCampaign.setStatus("Completed");
    subCampaign.setMessage("Completed");
    if(subCampaign != null && subCampaignService != null) //Check is not null to subCampaign before update
    subCampaignService.updateSubCampaign(subCampaign);
} catch (Exception e) {
     log.error("", e);
}
like image 92
Bhuwan Prasad Upadhyay Avatar answered Mar 27 '23 07:03

Bhuwan Prasad Upadhyay


I think the answer you are looking for is here

Please check below link

Correct way to persist Quartz triggers in database

And you can also check this link

Using Hibernate session with quartz

like image 36
Luffy Avatar answered Mar 27 '23 08:03

Luffy