使用quratz定時調用

最近在工作上需要定時調用的功能,定時調用在web中應用還是蠻多的,比如說課表提醒,每天晚上提醒一遍有什麼課要上啦,或者就像目前我需要完成的功能,定時的一個數據庫的數據導入到另一個數據庫中。

而quratz是一個完全由java編寫的開源作業調度框架。儘管Quartz框架整合了許多額外功能, 但就其簡易形式看,你會發現它易用得簡直讓人受不了!使用起來確實特別方便,也很實用。

廢話不多說,直接上!

首先需要quratz相關jar包,我使用的是quartz-2.2.1.jar。

接下來就需要一個job執行類和一個任務調度類。

任務調度類,在該類中制定corn表達式,通過該表達式來按你的要求來實現定時方式,比如每天某個時間運行。

package com.gisquest.djgx.modules.services;

import java.util.Properties;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;  
import org.quartz.Scheduler;  
import org.quartz.SchedulerFactory;  
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;  
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.gisquest.djgx.modules.sys.entity.WsDefine;
import com.gisquest.djgx.modules.sys.utils.DictUtils;

@Component
@Transactional(readOnly = true)
public class InvokeService {

    SchedulerFactory sf = null;
    Scheduler sched = null;

	// 點擊啓動按鈕調用的方法
	public void scheduler(WsDefine wsDefine,String basePath,String id) {
		String deftime = wsDefine.getDeftime();
		String month = "*";
		String year = "?";

		String schedName = "schedu"+id;
		String jobName = "job"+id;
		String groupName = "group"+id;
		String triggerName = "trigger"+id;
		String schedString="";
		try {
			Properties props = new Properties();
			props.put("org.quartz.scheduler.instanceName", schedName);
			props.put("org.quartz.threadPool.threadCount", "100");
			sf = new StdSchedulerFactory(props);
			if(sf.getScheduler(schedName) != null){
				sched = sf.getScheduler(schedName);  // 初始化調度器
			}else{
				sched = sf.getScheduler();  // 初始化調度器
			}
			JobDetail job = JobBuilder.newJob(QuartzJob.class)
					.withIdentity(jobName, groupName).build(); // 設置作業,具體操作在QuartzJob類裏
			job.getJobDataMap().put("wsurl", basePath+wsDefine.getUrl());//添加調用功能需要的熟悉
			job.getJobDataMap().put("jobid", wsDefine.getJobid());
			job.getJobDataMap().put("wsname", wsDefine.getName());
String[] str = deftime.split(":");
			 schedString = str[2] + " " + str[1] + " " +str[0]+ " " + "*"//這裏就是設定定時的表達式,我這裏將時間按“:”分割成str數組
					+ " " + month + " " + year;
			
			System.out.println(schedString);
			System.out.println(sched);
			CronTrigger trigger = (CronTrigger) TriggerBuilder
					.newTrigger()//創建觸發器
					.withIdentity(triggerName, groupName)//設定標示
					.withSchedule(CronScheduleBuilder.cronSchedule(schedString))//添加表達式
					.build(); // 設置觸發器
			sched.scheduleJob(job, trigger); // 設置調度作業
			sched.start(); // 開啓調度任務,執行作業
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	// 點擊停止按鈕調用的方法
	public void stopService(String id) {
		String schedName = "schedu"+id;
		try {
			if (sf.getScheduler(schedName) != null) {
				sf.getScheduler(schedName).shutdown();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}
這上面只使用了CronTrigger的方式,還有一種更簡單點的方式SimpleTrigger,該方式沒有cronTrigger方式更精確。在本文下面有CronTrigger表達式的配置格式。

job執行類,該類需要實現quratz的job接口,並實現execute方法,你要定時調用的功能就在該execute方法中調用。

<span style="font-size:18px;">package com.gisquest.djgx.modules.services;

import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
@Transactional(readOnly = true)
public class QuartzJob implements Job {
	private static final Logger log = LoggerFactory.getLogger(QuartzJob.class);
	
	@Override
	public void execute(JobExecutionContext context)
			throws JobExecutionException {
		try {
			JobDataMap dataMap = context.getJobDetail().getJobDataMap();
			String wsurl = dataMap.getString("wsurl");
			String jobid = String.valueOf(dataMap.getInt("jobid"));//從之前在任務調度中傳入的屬性
			String wsname = dataMap.getString("wsname");
			System.out.println(wsurl+jobid+wsname);
			WsService wsService = new WsService();
			System.out.println(wsService);
			wsService.callWebService(null,wsurl,"pushData",jobid,wsname);//定時調用的方法
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getLocalizedMessage());
		}
	}

}</span>

CronTrigger配置格式:
格式: [秒] [分] [小時] [日] [月] [周] [年]

序號 說明 是否必填 允許填寫的值 允許的通配符
1 0-59 , - * /
2 0-59 , - * /
3 小時 0-23 , - * /
4 1-31 , - * ? / L W
5 1-12 or JAN-DEC , - * /
6 1-7 or SUN-SAT , - * ? / L #
7 empty 或 1970-2099 , - * /

常用示例:

0 0 12 * * ? 每天12點觸發
0 15 10 ? * * 每天10點15分觸發
0 15 10 * * ? 每天10點15分觸發
0 15 10 * * ? * 每天10點15分觸發
0 15 10 * * ? 2005 2005年每天10點15分觸發
0 * 14 * * ? 每天下午的 2點到2點59分每分觸發
0 0/5 14 * * ? 每天下午的 2點到2點59分(整點開始,每隔5分觸發)
0 0/5 14,18 * * ? 每天下午的 2點到2點59分(整點開始,每隔5分觸發) 每天下午的 18點到18點59分(整點開始,每隔5分觸發)
0 0-5 14 * * ? 每天下午的 2點到2點05分每分觸發
0 10,44 14 ? 3 WED 3月分每週三下午的 2點10分和2點44分觸發
0 15 10 ? * MON-FRI 從週一到週五每天上午的10點15分觸發
0 15 10 15 * ? 每月15號上午10點15分觸發
0 15 10 L * ? 每月最後一天的10點15分觸發
0 15 10 ? * 6L 每月最後一週的星期五的10點15分觸發
0 15 10 ? * 6L 2002-2005 從2002年到2005年每月最後一週的星期五的10點15分觸發
0 15 10 ? * 6#3 每月的第三週的星期五開始觸發
0 0 12 1/5 * ? 每月的第一個中午開始每隔5天觸發一次
0 11 11 11 11 ? 每年的11月11號 11點11分觸發(光棍節)



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章