springboot集成定时任务

一、Quartz实现定时任务

1、引入依赖


    org.springframework.boot
    spring-boot-starter-quartz

2、application.yml 增加配置

org:
  quartz:
    trigger_key_name: job_trigger
    job_group: job_group
    cron_time: 0/5 * * * * ?

3、新建配置类

@Configuration
public class QuartzConfig {

    @Value("${org.quartz.trigger_key_name}")
    private String TRIGGER_KEY_NAME;
    @Value("${org.quartz.job_group}")
    private String JOB_GROUP;
    @Value("${org.quartz.cron_time}")
    private String CRON_TIME;

    @Autowired
    Scheduler scheduler;

    public void startJob() throws SchedulerException{
        //首先是通过 JobBuilder 创建JobDetail实例,QuartzJob 必须是实现了 Job 接口的实例
        JobDetail jobDetail = JobBuilder.newJob(QuartzJob.class).withIdentity(TRIGGER_KEY_NAME,JOB_GROUP).build();
        //构建触发器
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(CRON_TIME);
        CronTrigger cronTrigger = TriggerBuilder.newTrigger()
                                    .withIdentity(TRIGGER_KEY_NAME, JOB_GROUP)
                                    .withSchedule(cronScheduleBuilder).build();
        //将任务和触发器绑定到调度器
        scheduler.scheduleJob(jobDetail,cronTrigger);
        scheduler.start();
    }

}

4、新增Job任务类,必须实现 quartz 的Job接口

public class QuartzJob implements Job {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        logger.info("==== 定时任务 =====");
    }
}

5、控制器调用测试一下效果

@RequestMapping("/index")
    public String index(){
        try {
            quartzConfig.startJob();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return "index:content";
    }

  springboot集成定时任务_第1张图片

二、SpringTask实现定时任务

1、不需要引入依赖,直接在项目启动类增加注解

//启用自带定时任务
@EnableScheduling
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

2、定时任务(注:定时任务的类不能是抽象类,如果非要则需要有子类继承)

@Component
public class OrderTimeOutCancelTask {
    /**
     * 每10分钟扫描一次,扫描设定超时时间之前下的订单,如果没支付则取消该订单
     */
    @Scheduled(cron = "0 0/10 * ? * ?")
    private void cancelTimeOutOrder() {
    }
}

 

你可能感兴趣的:(后端)