org.springframework.boot spring-boot-starter-quartz 2.5.2
Quartz is a scheduled task framework that is commonly used insingle application projects. The scheduled tasks can be mainly divided into:
Tasks in memory: Generally defined and stored inside the project, if the project is restarted, if the task is not automatically executed , it will not be turned on again.
Persistent tasks: Store the characteristics of the task in the database. After the project is restarted, the originally executing task can be re-read and continued execution.
cornis used to control the time when the task is triggered.
I list some commonly used ones:
Trigger every second
"* * * * * *":
Every 5 Execute once per second
*/5 * * * * ?
Trigger every minute
"0 * * * * ?"
Trigger every hour
"0 * * * * ?"
Trigger once every day at 10 o'clock
"0 0 10 * * ?"
Trigger once every day at 0 o'clock
"0 0 0 * * ?"
You need to add the@EnableSchedulingannotation to the startup class.
Directly define an execution task, for example:
Output every secondTest
@Service public class ScheduleTest { @Scheduled(cron = "0/1 * * * * *") public void test() { System.out.println("测试"); } }
Startup class:
@SpringBootApplication @EnableScheduling public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
After startup, the corresponding content will be output in the console.
Here we need to define the task ourselves.
By implementing theJobinterface, a task can be defined, and we can manually control the opening of this task.
public class SimpleJob implements Job { @Override public void execute(JobExecutionContext context) { System.out.println("自定义任务"); } }
Import dependencies:
org.springframework.boot spring-boot-starter-web 2.3.6.RELEASE
Writing Controller, this is a fixed way of writing.
Specify the task:JobBuilder.newJob(task.class) .withIdentity(task name, task group).build();
Specify cron expression and create Trigger:
##CronScheduleBuilder.cronSchedule(cron expression);
TriggerBuilder.newTrigger().withIdentity(initiator name, starter group) .withSchedule(cron).build();
scheduler.scheduleJob (task type object, launcher object)
/** * @ClassName * @Description * @Author:chengyunlai * @Date * @Version 1.0 **/ @RestController public class DynamicScheduleController { @Autowired private Scheduler scheduler; @GetMapping("/addSchedule") public String addSchedule() throws SchedulerException { int random = ThreadLocalRandom.current().nextInt(1000); // 1. 创建JobDetail,指定定时任务实现类的类型 JobDetail jobDetail = JobBuilder.newJob(SimpleJob.class) .withIdentity("test-schedule" + random, "test-group").build(); // 2. 创建Trigger,并指定每3秒执行一次 CronScheduleBuilder cron = CronScheduleBuilder.cronSchedule("0/3 * * * * ?"); Trigger trigger = TriggerBuilder.newTrigger().withIdentity("test-trigger" + random, "test-trigger-group") .withSchedule(cron).build(); // 3. 调度任务 scheduler.scheduleJob(jobDetail, trigger); return "success"; }
Enter the address of the project through the browser, the default is
localhost:8080/addSchedule, after entering it, you can see that the console outputs the output content of the task execution.
SimpleJobscheduled task will not be restarted. The solution is to persist the task.Quartzprovides a solution, and SpringBoot simplifies this operation. We only need to configure: database, data source, and JDBC to operate the database.
mysql mysql-connector-java org.springframework.boot spring-boot-starter-jdbc com.alibaba druid 1.2.8
# 设置将定时任务的信息保存到数据库 spring.quartz.job-store-type=jdbc # 每次应用启动的时候都初始化数据库表结构 # 如果 spring.quartz.jdbc.initialize-schema 设置为 always 的话有个问题:每次重启应用的时候,跟 Quartz 相关的表会被删除重建! # 所以为了避免表被重复创建,我们可以提前创建表,然后将其指定为never spring.quartz.jdbc.initialize-schema=never # 数据库配置 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/scheduled?serverTimezone=GMT%2B8&useSSL=false&characterEncoding=utf-8 spring.datasource.username=root spring.datasource.password=root
jdbcjobstore:
quartz-2.3.0-SNAPSHOT \src\org\quartz\impl\jdbcjobstore
sqlfiles. Just find the sql file that matches your database. I use mysql .

scheduled. You should be able to see it from my URL.
localhost:8080/addSchedule, then refresh the database, you will find that the task is persisted After restarting the project, the task will still be executed automatically.
JobDetail jobDetail = JobBuilder.newJob(SimpleJob.class) .withIdentity(任务名,任务组).build();When pausing and resuming a task, you need to use
JobKey.jobKey (task name, task group)to get aJobKey, and then usescheduler.pauseJob(jobkey)can pause the task;scheduler.resumeJob(jobKey)resume the task.
jobkeyto represent the task. We also need to get the trigger. Similarly We also defined the launcher's name and group.
`TriggerBuilder.newTrigger().withIdentity(启动器的名字, 启动器的分组) .withSchedule(cron).build();`
TriggerKey.triggerKey((name of launcher, group of launcher);You can also gettriggerto represent the launcher.
通过以下顺序完整删除任务
scheduler.deleteJob(jobKey);
scheduler.unscheduleJob(triggerKey);
scheduler.pauseTrigger(triggerKey);
// 停止触发器
// 移除触发器
// 删除任务
// 暂停 @GetMapping("/pauseSchedule") public String pauseSchedule(String jobName, String jobGroup) throws SchedulerException { JobKey jobKey = JobKey.jobKey(jobName, jobGroup); // 获取定时任务 JobDetail jobDetail = scheduler.getJobDetail(jobKey); if (jobDetail == null) { return "error"; } scheduler.pauseJob(jobKey); return "success"; } // 恢复 @GetMapping("/remuseSchedule") public String remuseSchedule(String jobName, String jobGroup) throws SchedulerException { JobKey jobKey = JobKey.jobKey(jobName, jobGroup); // 获取定时任务 JobDetail jobDetail = scheduler.getJobDetail(jobKey); if (jobDetail == null) { return "error"; } scheduler.resumeJob(jobKey); return "success"; } // 删除定时任务 @GetMapping("/removeSchedule") public String removeSchedule(String jobName, String jobGroup, String triggerName, String triggerGroup) throws SchedulerException { TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroup); JobKey jobKey = JobKey.jobKey(jobName, jobGroup); Trigger trigger = scheduler.getTrigger(triggerKey); if (trigger == null) { return "error"; } // 停止触发器 scheduler.pauseTrigger(triggerKey); // 移除触发器 scheduler.unscheduleJob(triggerKey); // 删除任务 scheduler.deleteJob(jobKey); return "success"; }
The above is the detailed content of How to integrate Quartz with SpringBoot. For more information, please follow other related articles on the PHP Chinese website!