yantian yue
2023-10-20 4f58ba24b9a7e24dc38aa8eb9ca0b92c83e161ac
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package cn.stylefeng.guns.core.schedue.quartz;
 
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
 
/**
 * quartz的启动示例
 *
 * @author fengshuonan
 * @Date 2019/2/24 16:55
 */
public class StartQuartzExample implements CommandLineRunner {
 
    @Autowired
    private Scheduler scheduler;
 
    @Override
    public void run(String... args) throws Exception {
 
        // 启动调度器
        scheduler.start();
 
        //构建job信息
        JobDetail jobDetail = JobBuilder.newJob(SampleQuartzJob.class).withIdentity(SampleQuartzJob.class.getName(), "aaa").build();
 
        //表达式调度构建器(即任务执行的时间)
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("*/5 * * * * ?");
 
        //按新的cronExpression表达式构建一个新的trigger
        CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(SampleQuartzJob.class.getName(), "aaa")
                .withSchedule(scheduleBuilder).build();
 
        try {
            scheduler.scheduleJob(jobDetail, trigger);
 
        } catch (SchedulerException e) {
            System.out.println("创建定时任务失败" + e);
            throw new Exception("创建定时任务失败");
        }
    }
}