quartz cron
时间: 2023-09-13 11:09:09 浏览: 116
Quartz is a popular open-source job scheduling library in Java that allows developers to schedule tasks to run at specific times or intervals. It supports a cron-like syntax for defining schedules, known as Cron Triggers.
A cron expression is a string that represents a schedule in a specific format. It consists of six fields (second, minute, hour, day of month, month, day of week) separated by spaces. Each field can contain a specific value, a range of values, or wildcards to represent all possible values.
For example, the cron expression "0 0 12 * * ?" represents a schedule that triggers at 12 PM (noon) every day.
Quartz provides a CronTrigger class to create and manage cron-based schedules in Java applications. It allows you to define the schedule using the cron expression and associate it with a specific job to be executed.
Here's an example of using Quartz to schedule a job with a cron trigger in Java:
```java
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
public class QuartzExample {
public static void main(String[] args) throws SchedulerException {
// Define a job
JobDetail job = JobBuilder.newJob(MyJob.class)
.withIdentity("myJob", "group1")
.build();
// Define a trigger with a cron expression
Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity("myTrigger", "group1")
.withSchedule(CronScheduleBuilder.cronSchedule("0 0 12 * * ?"))
.build();
// Create a scheduler factory
SchedulerFactory schedulerFactory = new StdSchedulerFactory();
Scheduler scheduler = schedulerFactory.getScheduler();
// Schedule the job with the trigger
scheduler.scheduleJob(job, trigger);
// Start the scheduler
scheduler.start();
}
}
public class MyJob implements Job {
public void execute(JobExecutionContext context) throws JobExecutionException {
// Job logic goes here
System.out.println("Hello, Quartz!");
}
}
```
In this example, the `QuartzExample` class schedules a job (`MyJob`) to run at 12 PM every day using a cron trigger. When the trigger fires, the `execute` method of the `MyJob` class will be executed.
阅读全文