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

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

}


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

感谢您的建议!

最佳答案

您需要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;
    }
}


以及根据您的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代码。
我知道课程设计不好,但我担心的是尝试解决您的问题。

这是你想要的 ?

10-02 07:45