quartz学习笔记

导入maven依赖


    org.quartz-scheduler
    quartz
    2.3.0

该依赖会自动加载其他的依赖包,比如

编写自定义的job类,继承job

package com.lckoo.bear.module.demo.quartz;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

/**
 * 定义自己的job任务
 */
public class MyJob implements Job{

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        //编写具体的业务逻辑
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("d:MM:uuuu HH:mm:ss");

        System.out.println("当前时间            "+LocalTime.now());
        System.out.println("Hello World");
    }

}

创建 触发器和调度器


package com.lckoo.bear.module.demo.quartz;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.scheduling.annotation.Scheduled;

/**
 * test
 */
public class QuartzTest {
    public static void main(String[] args) {
        //创建一个jobdetail实例,绑定job
        JobDetail jobDetail = JobBuilder.newJob(MyJob.class)
                .withIdentity("job1","jobgroup")
                .build();
        //创建一个触发器
        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("trigger1","group1")
                .startNow()
                .withSchedule(
                        SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(2).repeatForever())
                .build();

        //创建scheduler 调度器
        SchedulerFactory schedulerFactory = new StdSchedulerFactory();
        try {
            Scheduler scheduler = schedulerFactory.getScheduler();
            scheduler.scheduleJob(jobDetail,trigger);
            scheduler.start();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }

    }
}

你可能感兴趣的:(quartz学习笔记)