quartz,springboot-quartz,线程任务

2017-06-16  本文已影响0人  bboymonk

1,简单实例

Job接口包含唯一方法execute(),将任务逻辑添加到该方法中。
package com.wjb.quartz;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
/**
 * Created by wjb on 2017/6/16.
 */
public class MyJob implements Job {
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd:HH:mm:ss:SSS");
        System.out.println("测试quartz任务:" + format.format(Calendar.getInstance().getTime()));
    }
}
StdSchedulerFactory.getScheduler()返回一个可运行的实例,然后创建调度任务的JobDetail实例,并传递3个参数给构造方法。第一个参数是任务名,用于引用该任务。第二个参数是任务组名,这里使用默认名,任务组名用于引用集合起来的一组任务,如可以使用Scheduler.pauseJobGroup()来暂停一组任务,每个组中的任务名是唯一的。第三个参数是实现特定任务的类。创建JobDetail实例后,需要创建一个Trigger,这里使用的是SimpleTrigger类,它提供了JDK Timer风格的触发器行为。传递给SimpleTrigger构造方法的两个参数分别是触发器名和任务组名,触发器名在它所在的任务组中必须是唯一的。接下来是设置触发器的一些属性,setStartTime()是设置启动时间,setRepeatInterval()是设置重复间隔,setRepeatCount()是设置重复次数。最后,scheduler.start()启动调度,终止调度可以用stop()方法。
package com.wjb.quartz;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import java.text.SimpleDateFormat;
import java.util.Calendar;
/**
* Created by wjb on 2017/6/16.
*/
public class TestJob {
   public static void main(String[] args) {
       SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd:HH:mm:ss:SSS");
       System.out.println("开始时间:" + format.format(Calendar.getInstance().getTime()));
       try {
//            通过schedulerFactory获取一个调度器
           Scheduler scheduler = new StdSchedulerFactory().getScheduler();
//            创建jobDetail实例,绑定Job实现类,指明job的名称,所在组的名称,以及绑定job类
           JobDetail jobDetail = JobBuilder.newJob(MyJob.class).withIdentity("wjb", "bboyGroup").build();
//            使用simpleTrigger规则
           Trigger trigger = TriggerBuilder.newTrigger().withIdentity("simpleTrigger", "triggerGroup")
                   .withSchedule(SimpleScheduleBuilder.repeatSecondlyForever(1).withRepeatCount(8))
                   .startNow().build();


//            使用cornTrigger规则
//            Trigger trigger = TriggerBuilder.newTrigger().withIdentity("simpleTrigger","triggerGroup")
//                    .withSchedule(CronScheduleBuilder.cronSchedule("0/15 * * * * ? *"))
//                    .startNow().build();
//            把作业和触发器注册到任务调度中
           scheduler.scheduleJob(jobDetail, trigger);
//            启动调度
           scheduler.start();
       } catch (SchedulerException e) {
           e.printStackTrace();
       }
   }
}

2,线程实现5分钟执行一次数据查询

package com.apply.business;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import com.apply.model.TWare;
import com.apply.service.WareService;

@Component
public class WareManager implements ApplicationContextAware, Runnable {
    private WareService wareService;
    private static ApplicationContext context = null;
    private static WareManager wareManager = new WareManager();
    private static Map<Integer, TWare> mapWare = new ConcurrentHashMap<Integer, TWare>();

    private WareManager() {
        
    }

    public static WareManager getInstance() {
        return wareManager;
    }
    
    public boolean isExist(Integer id) {
        return mapWare.containsKey(id);
    }
    
    public boolean isExist(BigDecimal price) {
        for (Integer key : mapWare.keySet()) {
            if (mapWare.get(key).getOriginal().equals(price)) {
                return true;
            }
        }
        
        return false;
    }
    
    public TWare getById(Integer id) {
        return mapWare.containsKey(id) ? mapWare.get(id) : null;
    }
    
    public List<TWare> getAll() {
        List<TWare> lstWare = new ArrayList<TWare>();
        for (Integer key : mapWare.keySet()) {
            lstWare.add(mapWare.get(key));
        }
        
        return lstWare;
    }

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        if (WareManager.context == null) {
            WareManager.context = context;
            this.wareService = context.getBean(WareService.class);
            new Thread(this).start();
        }
    }

    @Override
    public void run() {
        while (true) {
            try {
                List<TWare> lstWare = wareService.getAll();
                for (TWare ware : lstWare) {
                    mapWare.put(ware.getId(), ware);
                }
                
                Thread.sleep(300000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

3,springboot-quartz

SchedulerListener
package com.apply.config;

import org.quartz.SchedulerException;
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;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

/**
 * Created by Administrator on 2017/8/4.
 */
@Configuration
public class SchedulerListener implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    public IndentScheduler indentScheduler;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        try {
            indentScheduler.scheduleJobs();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(){
        return new SchedulerFactoryBean();
    }
}
IndentScheduler
package com.apply.config;

import com.apply.utils.IndentJob;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;

/**
 * Created by Administrator on 2017/8/4.
 */
@Component
public class IndentScheduler {
    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;

    public void scheduleJobs() throws SchedulerException{
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        startJob(scheduler);
    }
    private void startJob(Scheduler scheduler) throws SchedulerException{
        JobDetail jobDetail = JobBuilder.newJob(IndentJob.class)
                .withIdentity("job1", "group1").build();
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("0/5 * * * * ?");
        CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "group1")
                .withSchedule(scheduleBuilder).build();
        scheduler.scheduleJob(jobDetail,cronTrigger);
    }
}
IndentJob
package com.apply.utils;

import com.apply.service.indent.IndentService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Created by Administrator on 2017/8/4.
 */
public class IndentJob implements Job {
    @Autowired
    private IndentService indentService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println("quartz测试");

    }
}
CronTrigger能够提供复杂的触发器表达式的支持。CronTrigger是基于Unix Cron守护进程,它是一个调度程序,支持简单而强大的触发器语法。使用CronTrigger主要的是要掌握Cron表达式。Cron表达式包含6个必要组件和一个可选组件,如下表所示。

Cron表达式举例:

"30 * * * * ?" 每半分钟触发任务
"30 10 * * * ?" 每小时的10分30秒触发任务
"30 10 1 * * ?" 每天1点10分30秒触发任务
"30 10 1 20 * ?" 每月20号1点10分30秒触发任务
"30 10 1 20 10 ? *" 每年10月20号1点10分30秒触发任务
"30 10 1 20 10 ? 2011" 2011年10月20号1点10分30秒触发任务
"30 10 1 ? 10 * 2011" 2011年10月每天1点10分30秒触发任务
"30 10 1 ? 10 SUN 2011" 2011年10月每周日1点10分30秒触发任务
"15,30,45 * * * * ?" 每15秒,30秒,45秒时触发任务
"15-45 * * * * ?" 15到45秒内,每秒都触发任务
"15/5 * * * * ?" 每分钟的每15秒开始触发,每隔5秒触发一次
"15-30/5 * * * * ?" 每分钟的15秒到30秒之间开始触发,每隔5秒触发一次
"0 0/3 * * * ?" 每小时的第0分0秒开始,每三分钟触发一次
"0 15 10 ? * MON-FRI" 星期一到星期五的10点15分0秒触发任务
"0 15 10 L * ?" 每个月最后一天的10点15分0秒触发任务
"0 15 10 LW * ?" 每个月最后一个工作日的10点15分0秒触发任务
"0 15 10 ? * 5L" 每个月最后一个星期四的10点15分0秒触发任务
"0 15 10 ? * 5#3" 每个月第三周的星期四的10点15分0秒触发任务

上一篇 下一篇

猜你喜欢

热点阅读