首页 文章

如何在Java中使用Quartz Scheduler框架运行cron作业?

提问于
浏览
0

我在Java中使用Quartz Scheduler来运行cron作业 . 这是我第一次使用这个框架来运行cron作业,所以我有些困惑 .

我正在关注这个tutorial以更好地理解如何使用Quartz框架 .

我想每周和每个月都运行 JobA 所以我从基本的例子开始 -

这是我到目前为止的例子 .

public class JobA implements Job {

    @Override
    public void execute(JobExecutionContext context)
            throws JobExecutionException {
        System.out.println("Job A is runing");

        // print whether it is week or month
    }
}

下面是我的CronTriggerExample,它安排要运行的作业

public class CronTriggerExample {
    public static void main(String[] args) throws Exception {

        JobKey jobKeyA = new JobKey("jobA", "group1");
        JobDetail jobA = JobBuilder.newJob(JobA.class).withIdentity(jobKeyA)
                .build();

        Trigger trigger1 = TriggerBuilder
                .newTrigger()
                .withIdentity("dummyTriggerName1", "group1")
                .withSchedule(CronScheduleBuilder.cronSchedule("5 8 * * 6 ?"))
                .build();

        Scheduler scheduler = new StdSchedulerFactory().getScheduler();

        scheduler.start();
        scheduler.scheduleJob(jobA, trigger1);
    }
}

Problem Statement:-

我不知道如何使用上面的代码每周和每月运行JobA . 在我的案例中,一周和一个月的cron标签条目是什么?我不想在晚上8点到凌晨5点之间运行任何工作,任何随机日都可以 .

如果JobA每周都在运行,那么它应该打印出 one-weekreport_week . 但是如果JobA每个月都在运行,那么它应该打印 one-monthreport_one_month 所以接下来的问题是 - 有什么办法,我们可以在尝试运行时将参数传递给JobA吗?

2 回答

  • 3

    石英中7个cron字段的含义:

    second minute hour day month week year
    

    year 字段是可选的 . * 表示每个,例如, week 字段中的 * 表示每周,因此您应该在 week 字段和 month 字段中使用 * . 注意指定 week 字段时,不要忘记在 day 字段中使用 ? .

    我的示例cron条目为您的要求是:

    0 0 0 ? * *
    

    这意味着每周和每月00:00:00运行工作,请根据您的需要进行调整 .

    有关更多信息,请参阅:CronTrigger .

    我希望它有所帮助 .

  • 0
    You can pass JobData if required
    
    JobBuilder.newJob(JobClass.class);
    jobDetail = jobBuilder.usingJobData("Key", "VALUE")
                        .withIdentity(dbname.getSchemaName(), "group1").build();
    
    
    However for your case you need to modify cron expression provided in your cronschedular
    
    http://www.cronmaker.com/
    
    Follow above link to build cron expression
    

相关问题