Java Cron Expressions: Complete Guide
Cron expression is a format used to define the time rules for scheduled tasks. In Java, the Quartz framework can be used to execute scheduled tasks and define the time rules for task execution using Cron expressions.
First, import the relevant dependencies of the Quartz framework. You can add the following dependencies in Maven:
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.3.2</version>
</dependency>
Next, create a scheduled task using the following code and define the execution time rules using a Cron expression.
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
public class CronExample {
public static void main(String[] args) {
try {
// 创建调度器
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
// 定义任务
JobDetail job = JobBuilder.newJob(MyJob.class)
.withIdentity("myJob", "group1")
.build();
// 定义触发器,并使用Cron表达式定义任务的执行时间规则
Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity("myTrigger", "group1")
.withSchedule(CronScheduleBuilder.cronSchedule("0 0 12 * * ?")) // 每天中午12点执行
.build();
// 将任务和触发器添加到调度器中
scheduler.scheduleJob(job, trigger);
// 启动调度器
scheduler.start();
} catch (SchedulerException e) {
e.printStackTrace();
}
}
public static class MyJob implements Job {
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
System.out.println("定时任务执行");
}
}
}
In the code above, we have created a scheduler, defined a task (MyJob), and set the execution time rule using the Cron expression “0 0 12 * * ?” (to run the task every day at noon). Then we added the task and trigger to the scheduler and started it.
Once the scheduler is activated, the timed task will be executed according to the rules defined by the Cron expression. In the above code, the timed task will run at 12 o’clock noon every day and output “Timed task executed”.
It is important to note that Cron expression syntax is very flexible and can support the definition of many time rules, including every day, every hour, every minute, etc. For specific syntax details, refer to the official Quartz documentation.