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

时间:2013-09-27 12:56:44

标签: java cron quartz-scheduler

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

  

说明:

2013-09-302013-09-27投放作业,但仅限于2013-09-30

之间

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

请帮帮我。如果还有其他方法,请告诉我。

我在Google上看过很多资源,但我仍然找不到任何资源。

链接:

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

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

Does cron expression in unix/linux allow specifying exact start and end dates

更新

我写了一篇,但它没有用

09:00 AM - 12:00 PM

尝试将|------------------------------------------------------------------| | 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.

1 个答案:

答案 0 :(得分:5)

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

您可以尝试以下代码(编辑:适用于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替换cronSchedule(“0 0 9-12 * *?”)(“0 0 9-12?*?”)