JAVA定时器quartz的使用

.在pom.xml中添加maven依赖

<dependency>
			<groupId>org.quartz-scheduler</groupId>
			<artifactId>quartz</artifactId>
			<version>2.2.1</version>
		</dependency>
		<dependency>
			<groupId>org.quartz-scheduler</groupId>
			<artifactId>quartz-jobs</artifactId>
			<version>2.2.1</version>
		</dependency>

 

startFilter 类 tomcat启动后,定时器开启

public class startFilter extends BaseController implements Filter{

	/**
	 * 初始化
	 */
	public void init(FilterConfig fc) throws ServletException {
		this.startWebsocketInstantMsg();
		this.startWebsocketOnline();
		this.reductionDbBackupQuartzState();
	}



	/**
	 * web容器重启时,所有定时备份状态关闭
	 */
	public void reductionDbBackupQuartzState(){
		try {
			//DbFH.executeUpdateFH("update DB_TIMINGBACKUP set STATUS = '2'");
			QuartzManager.addJob("早上发短信通知报餐", DbNoticQuartzJob.class, "0 0 9 * * ?");//0 10 8
			QuartzManager.addJob("下午统计报餐人数", DbCountQuartzJob.class, "0 10 15 * * ?");//0 10 15
		}catch(Exception e){
		}
	}

}
QuartzManager类
package com.fh.util;

import java.util.Map;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;  
import org.quartz.SchedulerFactory;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.impl.StdSchedulerFactory;  
  
/** 定时任务管理类 
 * @author FH 3 13 59679 0 Q
 * @date 2016-4-9
 */
public class QuartzManager {  
    private static SchedulerFactory gSchedulerFactory = new StdSchedulerFactory();  //创建一个SchedulerFactory工厂实例
    private static String JOB_GROUP_NAME = "FH_JOBGROUP_NAME";  					//任务组
    private static String TRIGGER_GROUP_NAME = "FH_TRIGGERGROUP_NAME";  			//触发器组
  
    /**添加一个定时任务,使用默认的任务组名,触发器名,触发器组名  
     * @param jobName 任务名
     * @param cls 任务
     * @param time 时间设置,参考quartz说明文档
     */
    public static void addJob(String jobName, Class<? extends Job> cls, String time) {  
        try {  
            Scheduler sched = gSchedulerFactory.getScheduler();  										//通过SchedulerFactory构建Scheduler对象
            JobDetail jobDetail= JobBuilder.newJob(cls).withIdentity(jobName,JOB_GROUP_NAME).build();	//用于描叙Job实现类及其他的一些静态信息,构建一个作业实例
        	CronTrigger trigger = (CronTrigger) TriggerBuilder
        			.newTrigger()	 																	//创建一个新的TriggerBuilder来规范一个触发器
    				.withIdentity(jobName, TRIGGER_GROUP_NAME)											//给触发器起一个名字和组名
    				.withSchedule(CronScheduleBuilder.cronSchedule(time))
    				.build();
            sched.scheduleJob(jobDetail, trigger);  
            if (!sched.isShutdown()) {  
                sched.start();  	  // 启动  
            }  
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        }  
    }  
    
    /**添加一个定时任务,使用默认的任务组名,触发器名,触发器组名  (带参数)
     * @param jobName 任务名
     * @param cls 任务
     * @param time 时间设置,参考quartz说明文档
     */
    public static void addJob(String jobName, Class<? extends Job> cls, String time, Map<String,Object> parameter) {  
        try {  
            Scheduler sched = gSchedulerFactory.getScheduler();  										//通过SchedulerFactory构建Scheduler对象
            JobDetail jobDetail= JobBuilder.newJob(cls).withIdentity(jobName,JOB_GROUP_NAME).build();	//用于描叙Job实现类及其他的一些静态信息,构建一个作业实例
            jobDetail.getJobDataMap().put("parameterList", parameter);								//传参数
        	CronTrigger trigger = (CronTrigger) TriggerBuilder
        			.newTrigger()	 																	//创建一个新的TriggerBuilder来规范一个触发器
    				.withIdentity(jobName, TRIGGER_GROUP_NAME)											//给触发器起一个名字和组名
    				.withSchedule(CronScheduleBuilder.cronSchedule(time))
    				.build();
            sched.scheduleJob(jobDetail, trigger);  
            if (!sched.isShutdown()) {  
                sched.start();  	  // 启动  
            }  
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        }  
    }  
  
    /**添加一个定时任务 
     * @param jobName	任务名 
     * @param jobGroupName	任务组名 
     * @param triggerName	触发器名 
     * @param triggerGroupName	触发器组名 
     * @param jobClass	任务 
     * @param time	时间设置,参考quartz说明文档 
     */
    public static void addJob(String jobName, String jobGroupName,  
            String triggerName, String triggerGroupName, Class<? extends Job> jobClass,  
            String time) {  
        try {  
            Scheduler sched = gSchedulerFactory.getScheduler();  
            JobDetail jobDetail= JobBuilder.newJob(jobClass).withIdentity(jobName,jobGroupName).build();// 任务名,任务组,任务执行类
            CronTrigger trigger = (CronTrigger) TriggerBuilder	 // 触发器  
    				.newTrigger()
    				.withIdentity(triggerName, triggerGroupName)
    				.withSchedule(CronScheduleBuilder.cronSchedule(time))
    				.build();
            sched.scheduleJob(jobDetail, trigger);
            if (!sched.isShutdown()) {  
                sched.start();  	  // 启动  
            } 
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        }  
    }  
    
    /**添加一个定时任务  (带参数)
     * @param jobName	任务名 
     * @param jobGroupName	任务组名 
     * @param triggerName	触发器名 
     * @param triggerGroupName	触发器组名 
     * @param jobClass	任务 
     * @param time	时间设置,参考quartz说明文档 
     */
    public static void addJob(String jobName, String jobGroupName,  
            String triggerName, String triggerGroupName, Class<? extends Job> jobClass,  
            String time, Map<String,Object> parameter) {  
        try {  
            Scheduler sched = gSchedulerFactory.getScheduler();  
            JobDetail jobDetail= JobBuilder.newJob(jobClass).withIdentity(jobName,jobGroupName).build();// 任务名,任务组,任务执行类
            jobDetail.getJobDataMap().put("parameterList", parameter);								//传参数
            CronTrigger trigger = (CronTrigger) TriggerBuilder	 // 触发器  
    				.newTrigger()
    				.withIdentity(triggerName, triggerGroupName)
    				.withSchedule(CronScheduleBuilder.cronSchedule(time))
    				.build();
            sched.scheduleJob(jobDetail, trigger);
            if (!sched.isShutdown()) {  
                sched.start();  	  // 启动  
            } 
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        }  
    } 
  
    /** 修改一个任务的触发时间(使用默认的任务组名,触发器名,触发器组名) 
     * @param jobName	任务名 
     * @param time	新的时间设置
     */
    public static void modifyJobTime(String jobName, String time) {  
        try {  
            Scheduler sched = gSchedulerFactory.getScheduler();  							//通过SchedulerFactory构建Scheduler对象
            TriggerKey triggerKey = TriggerKey.triggerKey(jobName,TRIGGER_GROUP_NAME); 		//通过触发器名和组名获取TriggerKey
            CronTrigger trigger = (CronTrigger)sched.getTrigger(triggerKey);				//通过TriggerKey获取CronTrigger
            if (trigger == null) {  
                return;  
            }  
            String oldTime = trigger.getCronExpression();  
            if (!oldTime.equalsIgnoreCase(time)) {  
            	JobKey jobKey = JobKey.jobKey(jobName, JOB_GROUP_NAME);						//通过任务名和组名获取JobKey
            	JobDetail jobDetail = sched.getJobDetail(jobKey); 
                Class<? extends Job> objJobClass = jobDetail.getJobClass();  
                removeJob(jobName);  
                addJob(jobName, objJobClass, time);  
            }  
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        }  
    }  
    
    /**修改一个任务的触发时间 
     * @param triggerName	任务名称
     * @param triggerGroupName	传过来的任务名称
     * @param time	更新后的时间规则
     */
    public static void modifyJobTime(String triggerName, String triggerGroupName, String time) {  
        try {  
            Scheduler sched = gSchedulerFactory.getScheduler();  							//通过SchedulerFactory构建Scheduler对象
            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName,triggerGroupName); 	//通过触发器名和组名获取TriggerKey
            CronTrigger trigger = (CronTrigger)sched.getTrigger(triggerKey);				//通过TriggerKey获取CronTrigger
            if (trigger == null)  return;  
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(trigger.getCronExpression());
            String oldTime = trigger.getCronExpression();  
            if (!oldTime.equalsIgnoreCase(time)) {  
            	trigger = (CronTrigger)trigger.getTriggerBuilder()		//重新构建trigger
            			.withIdentity(triggerKey)
            			.withSchedule(scheduleBuilder)
            			.withSchedule(CronScheduleBuilder.cronSchedule(time))
        				.build();
            	sched.rescheduleJob(triggerKey, trigger);				//按新的trigger重新设置job执行
            }
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        }  
    }  
    
    /**移除一个任务(使用默认的任务组名,触发器名,触发器组名) 
     * @param jobName	任务名称
     */
    public static void removeJob(String jobName) {  
        try {  
            Scheduler sched = gSchedulerFactory.getScheduler();  
            TriggerKey triggerKey = TriggerKey.triggerKey(jobName,TRIGGER_GROUP_NAME); 	//通过触发器名和组名获取TriggerKey
            JobKey jobKey = JobKey.jobKey(jobName, JOB_GROUP_NAME);						//通过任务名和组名获取JobKey
            sched.pauseTrigger(triggerKey);	// 停止触发器  
            sched.unscheduleJob(triggerKey);// 移除触发器  
            sched.deleteJob(jobKey);		// 删除任务  
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        }  
    }  
    
    /**移除一个任务
     * @param jobName	任务名
     * @param jobGroupName	任务组名
     * @param triggerName	触发器名
     * @param triggerGroupName	触发器组名
     */
    public static void removeJob(String jobName, String jobGroupName,String triggerName, String triggerGroupName) {  
        try {  
            Scheduler sched = gSchedulerFactory.getScheduler();  
            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName,triggerGroupName); 	//通过触发器名和组名获取TriggerKey
            JobKey jobKey = JobKey.jobKey(jobName, jobGroupName);							//通过任务名和组名获取JobKey
            sched.pauseTrigger(triggerKey);	// 停止触发器  
            sched.unscheduleJob(triggerKey);// 移除触发器  
            sched.deleteJob(jobKey);		// 删除任务  
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        }  
    } 
    
    /**
     * 启动所有定时任务 
     */
    public static void startJobs() {  
        try {  
            Scheduler sched = gSchedulerFactory.getScheduler();  
            sched.start();  
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        }  
    }  
  
    /**
     * 关闭所有定时任务 
     */
    public static void shutdownJobs() {  
        try {  
            Scheduler sched = gSchedulerFactory.getScheduler();  
            if (!sched.isShutdown()) {  
                sched.shutdown();  
            }  
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        }  
    }  
}  
DbNoticQuartzJob类
package com.fh.controller.app.task;

import com.alibaba.fastjson.JSONObject;
import com.fh.entity.Page;
import com.fh.service.system.systemUser.SystemUserManager;
import com.fh.service.system.systemUser.impl.SystemUserService;
import com.fh.service.task.SysHolidayManager;
import com.fh.service.task.SystemReportMealManager;
import com.fh.service.task.impl.SysHolidayService;
import com.fh.service.task.impl.SystemTaskService;
import com.fh.util.PageData;
import com.fh.util.SendSms;
import com.fh.util.SpringBootBeanUtil;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class DbNoticQuartzJob implements Job {



    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        try {
            SystemUserManager systemUserService =SpringBootBeanUtil.getBean(SystemUserManager.class);
            SysHolidayManager sysHolidayService = SpringBootBeanUtil.getBean(SysHolidayManager.class);
            autoOver(systemUserService,sysHolidayService);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    private void autoOver( SystemUserManager systemUserService, SysHolidayManager sysHolidayService) throws Exception {
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        PageData pd = new PageData();
        List<PageData> holidayList = sysHolidayService.listAll(pd);
        List<String> dateList = new ArrayList<String>();
        holidayList.stream().forEach(e ->{
            dateList.add(e.getString("thetime"));
        });
        String tDay = sdf.format(addDay(now, 1));
        if(!dateList.contains(tDay)){
            pd.put("isSMSend", "0");
            List<PageData> userList = systemUserService.listAll(pd);
            String phones = "";
            for (int i=0;i<userList.size();i++){
                if(i!=userList.size()-1){
                    phones += userList.get(i).getString("mobile")+",";
                }else{
                    phones += userList.get(i).getString("mobile");
                }
            }

            System.out.println(phones);
            // 发送短信
            JSONObject jsonParam = new JSONObject();
            jsonParam.put("data", sdf.format(now));
            SendSms.sendSms(phones, "SMS_21****018", jsonParam.toString());
           // SendSms.sendSms(phones, "SMS_21****737", jsonParam.toString());
        }

    }

    // 增加或减少天数
    private Date addDay(Date date, int num) {
        Calendar startDT = Calendar.getInstance();
        startDT.setTime(date);
        startDT.add(Calendar.DAY_OF_MONTH, num);
        return startDT.getTime();
    }
}
SpringBootBeanUtil类
package com.fh.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringBootBeanUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (SpringBootBeanUtil.applicationContext == null) {
            SpringBootBeanUtil.applicationContext = applicationContext;
        }
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static Object getBean(String name) {
        return applicationContext.getBean(name);
    }

    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值