使用特定的开始,结束日期和时间限制运行Quartz Scheduler作业

我正在使用Quartz-Scheduler进行重复性任务,但我遇到了麻烦。 在我的服务器端,我的用户想要 09:00 AM - 12:00 PM 2013-09-30指定一些日期范围,例如From 2013-09-30

说明:

2013-09-272013-09-30之间运行一份工作,但仅限09:00 AM - 12:00 PM

我在为它编写Cron表达式时遇到了麻烦,而且我的用户是非技术性的,因此我的用户希望我从两个时间戳值自动创建Cron表达式。

请帮帮我。 如果有另一种方式,请告诉我。

我在谷歌上看过很多资源,但我仍然找不到任何东西。

链接:

http://quartz-scheduler.org/documentation/quartz-1.x/tutorials/crontrigger

http://quartz-scheduler.org/documentation/quartz-2.x/tutorials/tutorial-lesson-05

unix / linux中的cron表达式是否允许指定确切的开始和结束日期

更新

我写了一个,但它不起作用

 |------------------------------------------------------------------| | Seconds | Minutes | Hours | DayOfMonth | Month | DayOfWeek | Year| | | | | | | | | | 0 | 0 | 9-12 | 27-30 | 9 | ? | 2013| |------------------------------------------------------------------| 

试图将2013-09-27映射到2013-09-30但仅在09:00 AM - 12:00 PM

更新我也尝试过运行

 Trigger trigger = TriggerBuilder.newTrigger().withIdentity(NAME_TRIGGER_TASK_UPDATER, GROUP_TASK_TRIGGER) .withSchedule(CronScheduleBuilder.cronSchedule("0 0 9-12 19-22 10 ? *")).build(); 

但它不会给出任何错误,也不会进入我的执行方法

 cronSchedule("0 0 9-12 ? * ?") throws invalid schedule exception. 

下面的代码运行它而不考虑开始和结束日期。

 String startDateStr = "2013-09-27 00:00:00.0"; String endDateStr = "2013-09-31 00:00:00.0"; Date startDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").parse(startDateStr); Date endDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").parse(endDateStr); CronTrigger cronTrigger = newTrigger() .withIdentity("trigger1", "testJob") .startAt(startDate) .withSchedule(CronScheduleBuilder.cronSchedule("0 0 9-12 * * ?")) .endAt(endDate) .build(); 

当你说它不起作用时你会得到什么错误?

您可以尝试以下代码( 编辑:适用于Quartz 2.2)。 此方法不指定cron表达式中的开始/结束日期和年份,而是使用Trigger方法指定它们。 (注意:我自己没有测试过,让我知道它是否适合你)

编辑:我有机会测试这段代码,我运行下面的代码并不断更改系统时钟,所有触发器在开始到结束日期的上午9点到12点之间成功。

 public class CronJob { public static void main(String[] args) throws ParseException, SchedulerException { Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); JobDetail job = newJob(TestJob.class) .withIdentity("cronJob", "testJob") .build(); String startDateStr = "2013-09-27 00:00:00.0"; String endDateStr = "2013-09-31 00:00:00.0"; Date startDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").parse(startDateStr); Date endDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").parse(endDateStr); CronTrigger cronTrigger = newTrigger() .withIdentity("trigger1", "testJob") .startAt(startDate) .withSchedule(CronScheduleBuilder.cronSchedule("0 0 9-12 * * ?").withMisfireHandlingInstructionDoNothing()) .endAt(endDate) .build(); scheduler.scheduleJob(job, cronTrigger); scheduler.start(); } public static class TestJob implements Job { @Override public void execute(JobExecutionContext context) throws JobExecutionException { System.out.println("this is a cron scheduled test job"); } } } 

如果上面的代码不起作用,尝试用cronSchedule(“0 0 9-12?*?”)替换cronSchedule(“0 0 9-12 * *?”)