Use of timed task-quartz to achieve page management

Source: Internet
Author: User
Tags log log trim
Use of timed task-quartz to achieve page management
Use Spring+quartz to implement scheduled tasks for page management. Main Features:
1. The time expression and other information are configured in the database, so as to achieve page management.
2. You can manually perform or stop individual tasks, or you can make a task join or move out of the autorun list.

Here's how to get started, before you explain the version of the framework. spring3.2.4+quartz1.6.0
A. Configuration file
You only need to include the following in the spring configuration file:
<bean id= "Scheduler"  class= "Org.springframework.scheduling.quartz.SchedulerFactoryBean" >  
	</ bean>
	<bean id= "JobManager"  class= "Com.temobi.quartz.JobManager" >  
	</bean> 

Description: The Scheduler object is an object that spring manages timed tasks.
JobManager is the object that we customize to load the Scheduled Tasks list, which loads all the task lists and joins them to the Autorun list.
Two. JobManager Code:
public class JobManager implements Initializingbean  {
	private static final log log = Logfactory.getlog ( Jobmanager.class);
	@Autowired
	taskjobservice Taskjobservice;
	@Autowired
	Quartzmanager Quartzmanager;
	@Override public
	void Afterpropertiesset () throws Exception {
		loadalljob ();
	}
	private void Loadalljob () {
		list<taskjob> List =taskjobservice.gettasklist ();
		Quartzmanager.enablecronschedule (list);
	}
	
}


Description
1. Implement the Initializingbean interface in spring and overwrite the Afterpropertiesset method, this method will be executed when the application is started and other servlet execution is completed, here to load all the scheduled tasks, and join the scheduled task auto-run list.
2.quartzManager is our custom scheduled task management class, used to implement the functions we say at the beginning of our article.
Three. Quartzmanager Code
@Controller public class Quartzmanager {@Autowired Scheduler Scheduler;
	Private static final Log log = Logfactory.getlog (Quartzmanager.class); public void Enablecronschedule (list<taskjob> List) {for (Taskjob task:list) {schedulingjob job = new Scheduli
			Ngjob ();
			Job.setjobid (Task.getid ());
			Job.setjobname (Task.getjobname ());
			Job.setmemos (Task.getnote ());
			Job.setcronexpression (Task.getjobcronexpression ());
				try{String classname= task.getjobclass (). Trim ();
				Class clazz = Class.forName (className);
			Job.setstatefulljobexecuteclass (Clazz);
				}catch (Exception e) {e.printstacktrace ();
			Continue
			} jobdatamap Paramsmap = new Jobdatamap ();

			Paramsmap.put ("JobName", Task.getjobname ()); if (Task.getparamskey1 ()!=null && task.getparamsvalue1 ()!=null) {Paramsmap.put (Task.getparamskey1 (),
			Task.getparamsvalue1 ()); } if (Task.getparamskey2 ()!=null && task.getparamsvalue2 ()!=null) {Paramsmap.put (Task.getparamskeY2 (), task.getparamsvalue2 ()); } if (Task.getparamskey3 ()!=null && task.getparamsvalue3 ()!=null) {Paramsmap.put (Task.getparamskey3 (), task.
			GetParamsValue3 ());
			
			} enablecronschedule (Job, Paramsmap, true);
		Log.info ("System End Initialization task:" +task.getid () + ":" +task.getjobname () + ":" +task.getjobid ()); }}/** * Start a custom job * * @param schedulingjob * Custom Job * @param Paramsmap * passed to the job Row Data * @param isstatefull * is a synchronous timed task, true: synchronous, false: Async * @return Returns True if successful, otherwise false */public Boole An enablecronschedule (Schedulingjob schedulingjob, Jobdatamap paramsmap, Boolean isstatefull) {if (Schedulingjob = = nul
		L) {return false;
			} try {//scheduler = (scheduler) Applicationhelper.getbean ("Scheduler"); Crontrigger trigger = (Crontrigger) Scheduler.gettrigger (Schedulingjob.gettriggername (), Schedulingjob.getjobgroup (
			));
				if (null = = trigger) {//If the trigger is not present, create a jobdetail jobdetail = null; if (IsSTatefull) {jobdetail = new Jobdetail (Schedulingjob.getjobid (), Schedulingjob.getjobgroup (), Schedulingjob.get
				Statefulljobexecuteclass ()); } else {jobdetail = new Jobdetail (Schedulingjob.getjobid (), Schedulingjob.getjobgroup (), Schedulingjob.getjob
				Executeclass ());
				} jobdetail.setjobdatamap (Paramsmap); Trigger = new Crontrigger (Schedulingjob.gettriggername (), Schedulingjob.getjobgroup (), schedulingjob.getcronexpress
				Ion ());
			Scheduler.schedulejob (Jobdetail, Trigger);
				} else {//trigger already exists, then update the corresponding timing settings trigger.setcronexpression (schedulingjob.getcronexpression ());
			Scheduler.reschedulejob (Trigger.getname (), Trigger.getgroup (), trigger);
			}} catch (Exception e) {e.printstacktrace ();
		return false;
	} return true; }/** * Disable a job * * @param jobId * The ID of the job that needs to be disabled * @param jobgroupid * requires police jobgroupi D * @return Returns TRUE if successful, otherwise false */public boolean disableschedule (String jobID) {if (Jobid.equals ("))} {return false;
			} try {String jobgroupid= "DEFAULT";
			Trigger Trigger = Getjobtrigger (jobId, jobgroupid);
			if (null! = Trigger) {Scheduler.deletejob (jobId, jobgroupid);
			}} catch (Schedulerexception e) {e.printstacktrace ();
		return false;
	} return true; /** * Get Job Details * * @param jobId * Job ID * @param jobgroupid * Job's group ID * @retur N Job details, returns null if job does not exist */public Jobdetail Getjobdetail (string jobId, String jobgroupid) {if (Jobid.equals ("") | | Jobgroupid.equals ("") | | Null = = JobId | |
		Jobgroupid = = null) {return null;
		} try {return Scheduler.getjobdetail (jobId, jobgroupid);
			} catch (Schedulerexception e) {e.printstacktrace ();
		return null;
	 }}/** * get job corresponding trigger * * @param jobId * Job ID * @param jobgroupid * Job's group ID * The Trigger of the @return job, if Trigger does not exist, returns NULL */Public Trigger Getjobtrigger (String jobId,String jobgroupid) {if (Jobid.equals ("") | | | Jobgroupid.equals ("") | | Null = = JobId | |
		Jobgroupid = = null) {return null;
		} try {return Scheduler.gettrigger (jobId + "Trigger", jobgroupid);
			} catch (Schedulerexception e) {e.printstacktrace ();
		return null; }
	}

}


Description
1. There are three main ways to start a task, disable a task, and start multiple tasks. The auto-run list is added to start, and the auto-run list is disabled.
2.TaskJob is a Task object, which corresponds to the database table structure, and the database design is given later.
3. There are similar in the program,
Paramsmap.put (Task.getparamskey1 (), task.getparamsvalue1 ());
This code means if you: if you have a ParamsKey1 value of "username" in the database, the value of ParamsValue1 is "Zhangsang". Then you give the variable named "username" in the specific job and provide the set/ Get method, you can get the value "Zhangsang", this function is suitable for the fixed parameters of the scheduled task, and the parameter name you decide. We gave you three spare, you can also expand, the step is the database plus a field, in the above program Paramsmap put this field, of course you can not use parameters. Your database does not have any values configured to indicate that the scheduled task has no fixed parameters.
4.SchedulingJob is a bean for a timed task execution parameter. The value of the Taskjob object is processed into a Schedulingjob object, and then the API of the timed task is invoked with the value of the Schedulingjob object.
The main thing Schedulingjob objects do is that triggername and Jobgroup give default values respectively. Generates a Statefulljobexecuteclass class object based on classname.
Four. Schedulingjob Code:
public class Schedulingjob {public static final int js_enabled = 0;//task enabled state public static final int js_disabled = 1; Task disabled state public static final int js_delete = 2; Task deleted state private String jobId; The ID of the task, typically the ID of the bean defined by the private String jobName; Description of the task private String Jobgroup; The name of the group to which the task belongs private int jobstatus; Status of the task, 0: enabled, 1: Disabled, 2: Private String cronexpression has been deleted; Timed task run-time expression private String memos; Task Description Private class<?> statefulljobexecuteclass;//synchronous execution class, need to inherit from statefulmethodinvokingjob private class<? > jobexecuteclass;//asynchronous execution class, need to inherit from Methodinvokingjob/** * Get the Job's trigger name * @return */P
     Ublic String Gettriggername () {return this.getjobid () + "Trigger";
	} public String Getjobid () {return jobId;
	} public void Setjobid (String jobId) {this.jobid = JobId;
	} public String Getjobname () {return jobName; } public void Setjobname (String jobName) {this.jobname = JobnAme
		The public String Getjobgroup () {if (jobgroup==null) {jobgroup = Scheduler.default_group;
	} return Jobgroup;
	} public void Setjobgroup (String jobgroup) {this.jobgroup = Jobgroup;
	} public int Getjobstatus () {return jobstatus;
	} public void Setjobstatus (int jobstatus) {this.jobstatus = Jobstatus;
	} public String Getcronexpression () {return cronexpression;
	} public void Setcronexpression (String cronexpression) {this.cronexpression = cronexpression;
	} public String Getmemos () {return memos;
	} public void Setmemos (String memos) {This.memos = memos;
	} public class<?> Getstatefulljobexecuteclass () {return statefulljobexecuteclass; } public void Setstatefulljobexecuteclass (class<?> statefulljobexecuteclass) {This.statefulljobexecuteclass = s
	Tatefulljobexecuteclass;
	} public class<?> Getjobexecuteclass () {return jobexecuteclass; } public void Setjobexecuteclass (class<?> jobexecuteclass) {this.jobexecutEClass = Jobexecuteclass;
	} public static int getjs_enabled () {return js_enabled;
	} public static int getjs_disabled () {return js_disabled;
	} public static int getjs_delete () {return js_delete;
 }

}

Five. Specific job implementation
As long as you inherit the Quartzjobbean class, overwrite the Executeinternal method. In the job, it is possible to get the parameter value of the same name in the Jobdetail object in Jobdatamap (see Quartzmanager Class) in the way of the Get method. Sample code.
@Controller public class Contentjob extends quartzjobbean{@Autowired taskjobservice Taskjobservice;
	Private String begindate;
	
	Private String endDate; /** * Perform tasks manually * @param request */@RequestMapping ("/contentjobmanual.do") public void Manual (HttpServletRequest req
		uest) {String startdate=request.getparameter ("StartDate");
		String enddate=request.getparameter ("endDate");
		Taskjobservice Taskjobservice = (taskjobservice) applicationhelper.getbean ("Taskjobservice");
		map<string, string> param = new hashmap<string, string> ();
		SimpleDateFormat sdf=new SimpleDateFormat ("Yyyy-mm-dd");
		String Today=sdf.format (New Date ()); 
		if (Stringutils.isempty (StartDate)) {param.put ("begindate", today); 
		}else{param.put ("Begindate", StartDate); 
		} if (Stringutils.isempty (endDate)) {param.put ("endDate", today); 
		}else{param.put ("EndDate", endDate);
	} taskjobservice.callstatisticcontent (param); } @Override public void executeinternal (JobexeCutioncontext context) {Taskjobservice Taskjobservice = (taskjobservice) applicationhelper.getbean ("TaskJobService")
		;
		map<string, string> param = new hashmap<string, string> ();
		SimpleDateFormat sdf=new SimpleDateFormat ("Yyyy-mm-dd");
		String Today=sdf.format (New Date ()); 
		if (Stringutils.isempty (begindate)) {param.put ("begindate", today); 
		}else{param.put ("Begindate", begindate); 
		} if (Stringutils.isempty (endDate)) {param.put ("endDate", today); 
		}else{param.put ("EndDate", endDate);
	} taskjobservice.callstatisticcontent (param);
	} public String Getbegindate () {return begindate;
	} public void Setbegindate (String begindate) {this.begindate = begindate;
	} public String Getenddate () {return endDate;
	} public void Setenddate (String endDate) {this.enddate = endDate;
 }

Six. Perform a task manually. The job class can be declared as a @controller. Also write a method like the manual method in the previous example.
Extension: It is not possible to write an Autorun method and a manually executed method (that is, the Executeinternal method and the manual method). Because the Autorun method is not an action class, it is not in the Web environment, but is implemented through reflection. If the Executeinternal method is forcibly configured to have a Web-enabled method (that is, the class above add @controller, the method above add @requestmapping ("/contentjobmanual.do")) is also not possible, Because the method does not have a HttpServletRequest object, it cannot get parameters. Unless you have a timed task with no parameters. Of course you can't modify the parameter type of the method, because he is the method of overwriting Quartzjobbean.
Seven. Database design.
ID	VARCHAR2 n				
job_class	VARCHAR2 (255)	n			
job_name	VARCHAR2 (each)	n			
job_ Cron_expression	VARCHAR2 (x)	N		
job_service_bean	VARCHAR2 (x)	Y			
params_key1	VARCHAR2 y			
params_value1	VARCHAR2 y			
params_key2	VARCHAR2 (	y)			
params_value2	VARCHAR2 y			
params_key3	VARCHAR2 y			
params_value3	VARCHAR2 (	y)			
NOTE	VARCHAR2 (255)	y			
job_status	VARCHAR2 (1)	y			
updatetime	DATE	y			
job_autorun	VARCHAR2 (1)	Y
job_group	VARCHAR2 (y)				

Description: Job_status Indicates whether the task is valid, Job_autorun indicates whether to run automatically, Job_service_bean represents a manual execution of the request Url,job_class represents the full path of the job class, Job_group indicates which group the task belongs to. Convenient to the task of the Group management (batch start, prohibit, etc.), different from the Quartz API requirements of the same name parameter, in fact, you can also pass this value to the API. Other fields are better understood. The bean that corresponds to the table is taskjob.
Eight. Page management.
The main function is to add or remove a task from the Autorun queue (via the Quartzmanager object). and the task of additions and deletions to check. The sample code is as follows:
@Controller public class taskjobaction{private static final log log = Logfactory.getlog (Taskjobaction.class);
	@Autowired Taskjobservice Taskjobservice;
	
	@Autowired Quartzmanager Quartzmanager; @RequestMapping ("/enabletask.do") public void Enabletask (HttpServletRequest request, httpservletresponse response)
		Throws IOException {String parameterstr= "";
		Parameterstr = ioutils.tostring (Request.getinputstream (), inputconstant.char_set);
		Parameterstr = Stringutils.trim (PARAMETERSTR);
		Parameterstr =urldecoder.decode (parameterstr, "utf-8");
		map<string, string> p = jsonutil.getparametermap (PARAMETERSTR);
		String id=p.get ("id"); if (!
			Stringutils.isempty (ID)) {taskjob Task=taskjobservice.gettaskbyid (ID);
			List<taskjob> list=new arraylist<taskjob> ();
			List.add (Task);
			
			Quartzmanager.enablecronschedule (list);
			Task.setjobenabled ("Y"); Taskjobservice.update (Task);//Set task to autorun Status}} @RequestMapping ("/disabletask.do") public void DisabletAsk (HttpServletRequest request, httpservletresponse response) throws IOException {String parameterstr= "";
		Parameterstr = ioutils.tostring (Request.getinputstream (), inputconstant.char_set);
		Parameterstr = Stringutils.trim (PARAMETERSTR);
		Parameterstr =urldecoder.decode (parameterstr, "utf-8");
		map<string, string> p = jsonutil.getparametermap (PARAMETERSTR);
		String id=p.get ("id"); if (!
			Stringutils.isempty (ID)) {taskjob Task=taskjobservice.gettaskbyid (ID);
			
			Quartzmanager.disableschedule (Task.getjobid ());
			Task.setjobenabled ("N"); Taskjobservice.update (Task);//Set task to non-operational State}} @RequestMapping ("/add.do") public void Add (HttpServletRequest reque
			St, httpservletresponse response) throws IOException {String parameterstr= "";
			Parameterstr = ioutils.tostring (Request.getinputstream (), inputconstant.char_set);
			Parameterstr = Stringutils.trim (PARAMETERSTR);
			map<string, string> p = jsonutil.getparametermap (PARAMETERSTR); String Jobjson=p.get ("Jobjson ");
			Jobjson=urldecoder.decode (Jobjson, "utf-8");
			Taskjob Task=jsonutil.toobject (Jobjson, Taskjob.class);
			String Jobname=urldecoder.decode (Task.getjobname (), "utf-8");
			Task.setjobname (JobName); if (!
			Stringutils.isempty (Jobjson)) {Taskjobservice.insert (Task); }} @RequestMapping ("/update.do") public void Update (HttpServletRequest request, httpservletresponse response) th
			Rows IOException {String parameterstr= "";
			Parameterstr = ioutils.tostring (Request.getinputstream (), inputconstant.char_set);
			Parameterstr = Stringutils.trim (PARAMETERSTR);
			map<string, string> p = jsonutil.getparametermap (PARAMETERSTR);
			String jobjson=p.get ("Jobjson");
			Jobjson=urldecoder.decode (Jobjson, "utf-8");
			Taskjob Task=jsonutil.toobject (Jobjson, Taskjob.class);
			String Jobname=urldecoder.decode (Task.getjobname (), "utf-8");
			Task.setjobname (JobName); if (!
			Stringutils.isempty (Jobjson)) {taskjobservice.update (Task); }} @RequestMapping ("/DElete.do ") public void Delete (HttpServletRequest request, httpservletresponse response) throws IOException {String par
			Ameterstr= "";
			Parameterstr = ioutils.tostring (Request.getinputstream (), inputconstant.char_set);
			Parameterstr = Stringutils.trim (PARAMETERSTR);
			Parameterstr =urldecoder.decode (parameterstr, "utf-8");
			map<string, string> p = jsonutil.getparametermap (PARAMETERSTR);
			String idstr=p.get ("Idstr"); if (!
			Stringutils.isempty (IDSTR)) {taskjobservice.delete (IDSTR); }} @ResponseBody @RequestMapping ("/tasklist.do") Public Recordresultbean list (HttpServletRequest request, Httpser Vletresponse response, @RequestParam ("pageSize") int pageSize, @RequestParam ("StartIndex") int startIndex) throws Ioexc
		eption {int pagenum=startindex/pagesize+1;
		String startdate=request.getparameter ("StartDate");
		String enddate=request.getparameter ("endDate");
		String jobname=request.getparameter ("JobName"); if (! Stringutils.isempty (JobName)) {JobName=urldecoder.decode (JobName, "UTF-8");
		Jobname=urldecoder.decode (JobName, "UTF-8");
		} Recordresultbean Resultbean = new Recordresultbean ();
			try {Pager Pager = new Pager (Pagenum, pageSize);
			map<string, object> map = new hashmap<string, object> ();
			Map.put ("JobName", jobName);
			Pager.setkeys (map);
			Pager = Taskjobservice.findpage (pager);

			if (pager = = NULL | | Pager.gettotalcount () = = 0) {Resultbean.setresult (false);
				} else {Resultbean.setresult (true);
			Resultbean.setbean (pager);
		}}catch (Exception ex) {Log.warn (Jdkstacktrace.getjdkstrack (ex));
	} return Resultbean; }

Because a long time did not come to CSDN, see a lot of small partners in the program source code, in fact, this article is also my turn, the original source is not. But according to the original text and some of the information to do a regular release of the weather microblogging program, Shh+easyui architecture, also realized the function of page control task, because the time is very long, the source code for reference only, download address:

http://download.csdn.net/detail/a78460750/9865995

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.