调度持久性实体

时间:2011-04-12 08:42:44

标签: java hibernate spring quartz-scheduler

假设我有一个带有CronExpression字段的数据库实体:

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

}

将其纳入石英计划的最佳方法是什么?我使用Spring3和Hibernate。基本上我可以在我的DAO中安排它 - 任何时候创建或更新Job - 但我还需要在应用程序启动时安排所有现有的工作..

感谢您的建议!

1 个答案:

答案 0 :(得分:1)

您需要DAO/Repository才能从您的存储中获取所有cronExpression。我在内存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;
    }
}

和Component根据你的cronExpression创建石英调度程序。我称之为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);
        }
    }

}

您可以从http://www.mkyong.com/java/quartz-scheduler-example/获取RunMeJob and RunMeTask代码。 我知道课堂设计并不好,但我关心的是尝试解决你的问题。

这是你在找什么?