开发者

Scheduling a persistent entity

Let's say I have some DB entity with a CronExpression field:

@Entity
@Table(name = "job")
public class Job {
    ...
    private CronExpression cronExpression;

}

What is the best approach to p开发者_如何学JAVAut it onto quartz schedule? I use Spring3 and Hibernate. Basically I could schedule it in my DAO - anytime Job is created or updated - but I would also need to schedule all existed job at application start-up..

Thanks for your advices!


You need DAO/Repository to get all cronExpression from your storage. I create in memory DAO

@Repository
public class JobEntityDao {
    public List<JobEntity> findAll() {
        List<JobEntity> list = new ArrayList<JobEntity>();

        JobEntity job1 = new JobEntity("0 0 12 * * ?");
        JobEntity job2 = new JobEntity("0 15 10 ? * *");
        JobEntity job3 = new JobEntity("0 15 10 * * ?");

        list.add(job1);
        list.add(job2);
        list.add(job3);

        return list;
    }
}

And Component to create quartz scheduler based on your cronExpression. I call it QuartzExecutor

@Service
public class QuartzExecutor {


    private JobEntityDao jobEntityDao;

    @Autowired 
    public QuartzExecutor(JobEntityDao jobEntityDao) throws ParseException, SchedulerException {
        this.jobEntityDao = jobEntityDao; 
        init();
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    private void init() throws ParseException, SchedulerException {
        List<JobEntity> jobEntities = jobEntityDao.findAll();

        for (JobEntity jobEntity : jobEntities) {
            System.out.println(jobEntity.cronExpression);

            RunMeTask task = new RunMeTask();

            //specify your sceduler task details
            JobDetail job = new JobDetail();
            job.setName("runMeJob");
            job.setJobClass(RunMeJob.class);

            Map dataMap = job.getJobDataMap();
            dataMap.put("runMeTask", task);

            //configure the scheduler time
            CronTrigger trigger = new CronTrigger();
            trigger.setName("runMeJobTesting");
            trigger.setCronExpression(jobEntity.cronExpression);

            //schedule it
            Scheduler scheduler = new StdSchedulerFactory().getScheduler();
            scheduler.start();
            scheduler.scheduleJob(job, trigger);
        }
    }

}

you can get RunMeJob and RunMeTask code from http://www.mkyong.com/java/quartz-scheduler-example/. I Know the class design is not good, but my concern is try to solve your problem.

Is this what you are looking for ?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜