我在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-week
和 report_week
. 但是如果JobA每个月都在运行,那么它应该打印 one-month
和 report_one_month
所以接下来的问题是 - 有什么办法,我们可以在尝试运行时将参数传递给JobA吗?
2 回答
石英中7个cron字段的含义:
year
字段是可选的 .*
表示每个,例如,week
字段中的*
表示每周,因此您应该在week
字段和month
字段中使用*
. 注意指定week
字段时,不要忘记在day
字段中使用?
.我的示例cron条目为您的要求是:
这意味着每周和每月00:00:00运行工作,请根据您的需要进行调整 .
有关更多信息,请参阅:CronTrigger .
我希望它有所帮助 .