引用-自定义启动定时器

这里写自定义目录标题


https://blog.csdn.net/showhand2008/article/details/88313130?tdsourcetag=s_pcqq_aiomsg

导读:本文描述在springboot 2.x环境下怎么集成quartz。

一、添加quartz到项目中
在pom.xml中加入

org.quartz-scheduler quartz 2.2.1 特别注意application入口类的注解,这里一定要使用@SpringBootApplication,它是一个复合注解,包括@ComponentScan,和@SpringBootConfiguration,@EnableAutoConfiguration,我们这里用到了EnableAutoConfiguration的特性,以使得quartz进行了自动注解。

@SpringBootApplication
public class AdminApplication {

public static void main(String[] args) {
    SpringApplication.run(AdminApplication.class, args);
}

}
二、自定义job,用来处理业务逻辑
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class SchedulerQuartzJob implements Job {
private void before() {
System.out.println(“任务开始执行”);
}

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
    before();

    System.out.println("开始:" + System.currentTimeMillis());
    // TODO 业务
    JobDataMap jdMap = context.getJobDetail().getJobDataMap();  //获得传递过来的参数
    System.out.println(jdMap.get("user"));
    System.out.println("结束:" + System.currentTimeMillis());
    after();
}

private void after() {
    System.out.println("任务开始执行");
}

}
二、启动job
@RequestMapping(value = “testTask”, method = RequestMethod.POST)
public void testTask(HttpServletRequest request)throws SchedulerException {
JobDetail jobDetail = JobBuilder.newJob(SchedulerQuartzJob.class).withIdentity(“job2”, “group2”).build();
jobDetail.getJobDataMap().put(“user”, “Tom”); //给自定义任务传值
CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(“0 0/1 * * * ?”);
CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(“job2”, “group2”)
.withSchedule(cronScheduleBuilder).build();
scheduler.scheduleJob(jobDetail, cronTrigger);
}

//=附加Trigger常用功能代码======
Trigger trigger = TriggerBuilder.newTrigger().withIdentity(“Trigger_HelloQuartz”, “group1”) // 定义name/group
// .startNow()//一旦加入scheduler,立即执行
.startAt(new Date(System.currentTimeMillis() + 5000))// 5秒后执行
.withSchedule(SimpleScheduleBuilder.simpleSchedule() // 使用SimpleTrigger
.withIntervalInSeconds(2) // 每隔2秒执行一次
.withRepeatCount(1))// 重复1次,共计2次
// .repeatForever()) //一直执行,奔腾到老不停歇
.build();
运行结果如下:

下面补充一下,如何自定义调度器,开发者可以更加定制化的实现自己的功能

一、自定义调度器
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.Date;

@Configuration
public class MyQuartzScheduler {
// 任务调度
@Autowired
private Scheduler scheduler;

/**
 * 开始执行所有任务
 *
 * @throws SchedulerException
 */
public void startJob() throws SchedulerException {
    scheduler.start();
}

/**
 * 获取Job信息
 *
 * @param name
 * @param group
 * @return
 * @throws SchedulerException
 */
public String getJobInfo(String name, String group) throws SchedulerException {
    TriggerKey triggerKey = new TriggerKey(name, group);
    CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
    return String.format("time:%s,state:%s", cronTrigger.getCronExpression(),
            scheduler.getTriggerState(triggerKey).name());
}

/**
 * 修改某个任务的执行时间
 *
 * @param name
 * @param group
 * @param time
 * @return
 * @throws SchedulerException
 */
public boolean modifyJob(String name, String group, String time) throws SchedulerException {
    Date date = null;
    TriggerKey triggerKey = new TriggerKey(name, group);
    CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
    String oldTime = cronTrigger.getCronExpression();
    if (!oldTime.equalsIgnoreCase(time)) {
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(time);
        CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(name, group)
                .withSchedule(cronScheduleBuilder).build();
        date = scheduler.rescheduleJob(triggerKey, trigger);
    }
    return date != null;
}

/**
 * 暂停所有任务
 *
 * @throws SchedulerException
 */
public void pauseAllJob() throws SchedulerException {
    scheduler.pauseAll();
}

/**
 * 暂停某个任务
 *
 * @param name
 * @param group
 * @throws SchedulerException
 */
public void pauseJob(String name, String group) throws SchedulerException {
    JobKey jobKey = new JobKey(name, group);
    JobDetail jobDetail = scheduler.getJobDetail(jobKey);
    if (jobDetail == null)
        return;
    scheduler.pauseJob(jobKey);
}

/**
 * 恢复所有任务
 *
 * @throws SchedulerException
 */
public void resumeAllJob() throws SchedulerException {
    scheduler.resumeAll();
}

/**
 * 恢复某个任务
 *
 * @param name
 * @param group
 * @throws SchedulerException
 */
public void resumeJob(String name, String group) throws SchedulerException {
    JobKey jobKey = new JobKey(name, group);
    JobDetail jobDetail = scheduler.getJobDetail(jobKey);
    if (jobDetail == null)
        return;
    scheduler.resumeJob(jobKey);
}

/**
 * 删除某个任务
 *
 * @param name
 * @param group
 * @throws SchedulerException
 */
public void deleteJob(String name, String group) throws SchedulerException {
    JobKey jobKey = new JobKey(name, group);
    JobDetail jobDetail = scheduler.getJobDetail(jobKey);
    if (jobDetail == null)
        return;
    scheduler.deleteJob(jobKey);
}

public void scheduleJob(JobDetail jobDetail, CronTrigger cronTrigger) throws SchedulerException{
    scheduler.scheduleJob(jobDetail, cronTrigger);
}

}
二、随springboot框架启动
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;

@Configuration
public class ApplicationStartQuartzJobListener implements ApplicationListener {
@Autowired
private MyQuartzScheduler myQuartzScheduler;

/**
 * 初始启动quartz
 */
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
    try {
        myQuartzScheduler.startJob();
        System.out.println("任务已经启动...");
    } catch (SchedulerException e) {
        e.printStackTrace();
    }
}

/**
 * 初始注入scheduler
 * @return
 * @throws SchedulerException
 */
@Bean
public Scheduler scheduler() throws SchedulerException{
    SchedulerFactory schedulerFactoryBean = new StdSchedulerFactory();
    return schedulerFactoryBean.getScheduler();
}

}
三、如何调用
@Autowired
private MyQuartzScheduler myQuartzScheduler;

@RequestMapping(value = “testTask”, method = RequestMethod.POST)
public void testTask(HttpServletRequest request)throws SchedulerException {
JobDetail jobDetail = JobBuilder.newJob(SchedulerQuartzJob.class).withIdentity(“job2”, “group2”).build();
jobDetail.getJobDataMap().put(“user”, “Tom”);
CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(“0 0/1 * * * ?”);
CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(“job2”, “group2”)
.withSchedule(cronScheduleBuilder).build();
//这里只需要把之前的Scheduler换成myQuartzScheduler即可
myQuartzScheduler.scheduleJob(jobDetail, cronTrigger);
}

你可能感兴趣的:(Java)